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

拜拜、爱过 提交于 2019-11-28 09:16:31

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.

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>())));
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!