MVC源代码单例模式

时间:2010-10-04 15:40:43

标签: asp.net-mvc-2

为什么.net MVC源代码ControllerBuilder使用委托来分配控制器工厂?:

private Func<IControllerFactory> _factoryThunk;

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

为什么不能直接分配ControllerFactory?,即:

private IControllerFactory _factory;

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

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

1 个答案:

答案 0 :(得分:4)

_factoryThunk当前定义为Func<IControllerFactory>的原因是它是支持两种重载的通用方法:

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

第一个的实现使用_factoryThunkFunc的事实,通过使用Func懒惰地Activator实例化Type来声明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; }; 内联:

_factoryThunk

因此,其他重载看起来像是虚假实现的原因是,因为Func被声明为_factoryThunk = controllerFactory; ,所以你建议的行甚至不会被编译:

_factoryThunk

Func<IControllerFactory>controllerFactoryIControllerFactory是{{1}} - 不兼容的类型。