我在哪里为StructureMap嵌套容器注册HttpContextBase?

时间:2016-08-11 18:18:17

标签: c# asp.net-mvc-5 inversion-of-control structuremap structuremap4

我是IoC的新手,并将Nuget Package StructureMap.MVC5安装到我的MVC项目中 我正在尝试注册以下内容:
For<HttpContextBase>().Use(() => new HttpContextWrapper(HttpContext.Current))

根据我正在阅读的内容,我需要在嵌套容器中引用它,并且我在包中附带的StructureMapDependencyScope.cs文件中看到了对嵌套容器的引用。但是,我不知道在哪里/如何用它来注册这个HttpContextBase。

我尝试从StructuremapMvc.cs文件中注册它,如下所示:

public static class StructuremapMvc {

        public static StructureMapDependencyScope StructureMapDependencyScope { get; set; }

        public static void End() {
            StructureMapDependencyScope.Dispose();
        }

        public static void Start() {
            IContainer container = IoC.Initialize();
            StructureMapDependencyScope = new StructureMapDependencyScope(container);

            StructureMapDependencyScope.CreateNestedContainer();
            StructureMapDependencyScope.CurrentNestedContainer.Configure(x =>
            {
                x.For<IUserIdentity>().Use<CurrentUser>();
                x.For<HttpContextBase>().Use(() => new HttpContextWrapper(HttpContext.Current));
            });

            DependencyResolver.SetResolver(StructureMapDependencyScope);
            DynamicModuleUtility.RegisterModule(typeof(StructureMapScopeModule));
        }
    }

但那不起作用。我从HttpContext内的StructureMapDependencyScope.cs属性收到错误。

1 个答案:

答案 0 :(得分:0)

您的解决方案应包含名为DefaultRegistry的类,您可以将注册放在那里。嵌套容器将自动从父级继承此注册。