IoC in class library. Where to bootstrap

前端 未结 4 640
自闭症患者
自闭症患者 2020-12-13 02:39

I\'m using a class library that can be reused by other components. In this class library I\'m using unity for dependency injection. For this class library I create a test pr

4条回答
  •  爱一瞬间的悲伤
    2020-12-13 02:57

    O.K Create a library named Project.Ioc. Install Unity here. Reference the other layers to Ioc library. And Ioc Library to presentation layer. Create a class named UnityHelper.

    /// 
    /// Bind the given interface in request scope
    /// 
    public static class IocExtensions
    {
        public static void BindInRequestScope(this IUnityContainer container) where T2 : T1
        {
            container.RegisterType(new HierarchicalLifetimeManager());
        }
    
        public static void BindInSingletonScope(this IUnityContainer container) where T2 : T1
        {
            container.RegisterType(new ContainerControlledLifetimeManager());
        }
    }
    
    /// 
    /// The injection for Unity
    /// 
    public static class UnityHelper
    {
    
        public static IUnityContainer Start()
        {
            var container = BuildUnityContainer();
    
            DependencyResolver.SetResolver(new Unity.Mvc4.UnityDependencyResolver(container));
    
            return container;
        }
    
        /// 
        /// Inject
        /// 
        /// 
        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();
    
            // register all your components with the container here
            // it is NOT necessary to register your controllers
    
            // Database context, one per request, ensure it is disposed
            container.BindInRequestScope();
            container.BindInRequestScope();
    
            //Bind the various domain model services and repositories that e.g. our controllers require         
            container.BindInRequestScope();
    
            container.BindInRequestScope();
    
            //container.BindInRequestScope();
    
            return container;
        }
    }
    

    Check out the MvcForum project. There is MvcForm.Ioc class library. The library gets other Layer references. There are only one class named UnityHelper.

    https://github.com/leen3o/mvcforum

    i hope this is wat you are looking for.

提交回复
热议问题