如何访问Unity DI容器?

时间:2013-12-16 18:28:19

标签: c# dependency-injection unity-container

我正在使用Unity Mvc4软件包,它有一个在Application Start

上运行的bootstrap类(如下所示)

如何在不使用脏的静态属性的情况下访问我的容器?

public static class Bootstrapper
    {
        public static IUnityContainer Container { get; set; }
        public static IUnityContainer Initialise()
        {
            Container = BuildUnityContainer();
            DependencyResolver.SetResolver(new UnityDependencyResolver(Container));
            return Container;
        }

        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();
            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();    
            RegisterTypes(container);
            RegisterInstances(container);
            return container;
        }

        public static void RegisterTypes(IUnityContainer container)
        {
            container.RegisterType<IDataAccessHelper, DataAccessHelper>();
        }

        public static void RegisterInstances(IUnityContainer container)
        {
            container.RegisterInstance<GlobalHelper>(new GlobalHelper());
        }

    }

0 个答案:

没有答案