asp.net-mvc-2 - MVC 源代码单例模式

标签 asp.net-mvc-2

为什么.net MVC源代码ControllerBuilder使用委托(delegate)来分配 Controller 工厂?:

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);
}

最佳答案

原因_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;
_factoryThunkFunc<IControllerFactory>controllerFactoryIControllerFactory -- 不兼容的类型。

关于asp.net-mvc-2 - MVC 源代码单例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3856777/

相关文章:

asp.net-mvc-2 - 我可以在 Global.asax 以外的地方注册自定义模型绑定(bind)器吗?

asp.net-mvc-2 - MVC 2 - 如何设置 actionlink 的目标命名空间

jquery - 如何使用jquery调用html.actionlink

asp.net-mvc-2 - 在 asp.net web 应用程序中转录语音到文本的最佳选择是什么?

.net - HTML Helper不再能够推断类型参数

ASP.NET MVC : DropDownList validation

c# - 使用编辑器模板 MVC 进行日期时间格式化

asp.net-mvc-2 - 如何通过代码隐藏获取在 mvc 2 中运行的完整服务器名和端口

asp.net-mvc - asp.net mvc 选择更改重定向到操作

asp.net-mvc-3 - 使用 AutoMapper 将元数据传输到 View 模型的技术