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 having a hard time finding which terms to use in Google to come up with the unity equivalent if there is one.
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<IProductView>()))
.As<ProductPresenter>()
.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<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>())));
}
}