【问题标题】:Where to initialize ObjectFactory in ASP.NET MVC 3?在哪里初始化 ASP.NET MVC 3 中的 ObjectFactory?
【发布时间】:2012-03-05 12:39:32
【问题描述】:

我需要在 ASP.NET MVC 3 应用程序中初始化 StructureMap.ObjectFactory

ObjectFactory.Initialize(x => x.For<Db>().HttpContextScoped().Use<Db>());

我必须在Application_BeginRequestApplication_Start 中进行吗?

【问题讨论】:

    标签: c# .net dependency-injection inversion-of-control structuremap


    【解决方案1】:

    作为一般规则,您应该始终在Application_Start 事件处理程序中设置您的 IoC 容器,因为它只需要在应用程序的生命周期内发生一次

    在 StructureMap 的情况下,the documentation recommendscontainer configuration code 分隔在一个单独的Bootstrapper 类中:

    public static class Bootstrapper
    {
        public static void Bootstrap()
        {
            // ObjectFactory.Initialize(...
        }
    }
    

    然后您从 Application_Start 事件处理程序调用它:

    protected void Application_Start()
    {
        Bootstrapper.Bootstrap();
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-23
      • 1970-01-01
      • 2011-05-08
      • 2014-04-27
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      相关资源
      最近更新 更多