gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:51:12 24 4
gpt4 key购买 nike

我对 Autofac 相当熟悉,我非常喜欢 Autofac 的一项功能是模块注册。有谁知道我如何使用 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<IProductView>()))
.As<ProductPresenter>()
.ContainerScoped();
}
}

最佳答案

实际上,您可以使用 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>())));
}
}

关于c# - 我可以像在 Autofac 中那样在 Unity 中的模块中注册我的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3427674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com