开发者

MVC source code singleton pattern

开发者 https://www.devze.com 2023-01-18 12:39 出处:网络
Why does .net MVC source code ControllerBuilder use a delegate to assign the controller factory?: private Func<IControllerFactory> _factoryThunk;

Why does .net MVC source code ControllerBuilder use a delegate to assign the controller factory?:

private Func<IControllerFactory> _factoryThunk;

public void SetControllerFactory(IControllerFactory controllerFactory) {
    _factoryThunk = () => controllerFactory;
}

W开发者_如何转开发hy can't it just assign the ControllerFactory directly?, ie:

private IControllerFactory _factory;

public void SetControllerFactory(IControllerFactory controllerFactory) {
    _factory = controllerFactory;
}

public void SetControllerFactory(Type controllerFactoryType) {
    _factory = (IControllerFactory)Activator.CreateInstance(controllerFactoryType);
}


The reason that _factoryThunk is currently defined as a Func<IControllerFactory> is that it's a generic means to support both overloads:

void SetControllerFactory(Type);
void SetControllerFactory(IControllerFactory);

The implementation of the first one uses the fact that _factoryThunk is a Func by declaring that Func inline by using Activator to instantiate the Type lazily:

this._factoryThunk = delegate {
    IControllerFactory factory;
    try
    {
        factory = (IControllerFactory) Activator.CreateInstance(controllerFactoryType);
    }
    catch (Exception exception)
    {
        throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, MvcResources.ControllerBuilder_ErrorCreatingControllerFactory, new object[] { controllerFactoryType }), exception);
    }
    return factory;
};

Therefore, the reason the other overload looks like it has a spurious implementation is that since _factoryThunk is declared as a Func, the line you propose wouldn't have even compiled:

_factoryThunk = controllerFactory;

_factoryThunk is a Func<IControllerFactory> whereas controllerFactory is an IControllerFactory -- incompatible types.

0

精彩评论

暂无评论...
验证码 换一张
取 消