我可以像在Autofac中那样在Unity中的模块中注册我的类型吗?

我对Autofac非常熟悉,我非常喜欢Autofac的一个function是注册模块。 有谁知道我怎么能用Unity做到这一点? 如果有的话,我很难找到在Google中使用哪些术语来提出等效的统一。

public class Global : HttpApplication, IContainerProviderAccessor { private static IContainerProvider _containerProvider; protected void Application_Start(object sender, EventArgs e) { var builder = new ContainerBuilder(); builder.RegisterModule(new MyWebModule()); _containerProvider = new ContainerProvider(builder.Build()); } [...] public IContainerProvider ContainerProvider { get { return _containerProvider; } } } public class MyWebModule: Module { protected override void Load(ContainerBuilder builder) { builder.RegisterModule(new ApplicationModule()); builder.RegisterModule(new DomainModule()); } } public class ApplicationModule: Module { protected override void Load(ContainerBuilder builder) { builder.Register(c => new ProductPresenter(c.Resolve())) .As() .ContainerScoped(); } } 

你不能。 只需使用Autofac或Windsor。 您会发现Unity中缺少很多东西 ,并且它们以意想不到的方式运行。 这不值得你花时间。

实际上,您可以使用Unity容器扩展轻松完成。

 public class Global : HttpApplication, IContainerProviderAccessor { private static IContainerProvider _containerProvider; protected void Application_Start(object sender, EventArgs e) { var container = new UnityContainer(); container.AddNewExtension(); _containerProvider = new ContainerProvider(container); } [...] public IContainerProvider ContainerProvider { get { return _containerProvider; } } } public class MyWebModule : UnityContainerExtension { protected override void Initialize() { Container.AddNewExtension(); Container.AddNewExtension(); } } public class ApplicationModule: UnityContainerExtension { protected override void Initialize() { Container.RegisterType( new ContainerControlledLifetimeManager(), new InjectionFactory(c => new ProductPresenter(c.Resolve()))); } }