Can I register my types in modules in Unity like I can in Autofac?

前端 未结 2 1178
星月不相逢
星月不相逢 2020-12-09 20:14

I am fairly familiar with Autofac and one feature that I really love about Autofac is the registering of modules. Does anyone know how I can do this with Unity? I\'m havin

相关标签:
2条回答
  • 2020-12-09 20:57

    Actually, you can do trivially with Unity container extensions.

    public class Global : HttpApplication, IContainerProviderAccessor
    {
       private static IContainerProvider _containerProvider;
    
       protected void Application_Start(object sender, EventArgs e)
       {
          var container = new UnityContainer();
          container.AddNewExtension<MyWebModule>();
    
          _containerProvider = new ContainerProvider(container);
       }
    
    [...]
    
       public IContainerProvider ContainerProvider
       {
          get { return _containerProvider; }
       }
    }
    
    public class MyWebModule : UnityContainerExtension
    {
        protected override void Initialize()
        {
            Container.AddNewExtension<ApplicationModule>();
            Container.AddNewExtension<DomainModule>();
        }
    }
    
    public class ApplicationModule: UnityContainerExtension
    {
        protected override void Initialize()
        {
            Container.RegisterType<ProductPrensenter>(
                new ContainerControlledLifetimeManager(),
                new InjectionFactory(c => new ProductPresenter(c.Resolve<IProductView>())));
        }
    }
    
    0 讨论(0)
  • 2020-12-09 20:58

    You can't. Just use Autofac or Windsor. You will find there's a lot missing in Unity and what's there works in unexpected ways. It's just not worth your time.

    0 讨论(0)
提交回复
热议问题