如何配置我的统一容器以解析依赖对象树? 假设我们有这样的类:
public class Foo : IFoo
{
[Dependency]
public IBar Bar { get; set; }
}
public class Bar : IBar
{
[Dependency]
public IRepository Repository { get; set; }
}
public class Repository : IRepository
{
[Dependency]
public IService Service { get; set; }
}
我想解析 Foo: Container.ResolveAll();
是否可以解析无限嵌套的依赖对象?
最佳答案
构建依赖树(依赖图)是构建 DI 库的目的。
最佳实践是使用构造函数注入(inject)而不是属性注入(inject)。这也消除了让您的类了解有关 DI 库的任何信息的需要。
所以第一步是重构构造函数注入(inject),如下所示:
public class Foo : IFoo
{
private readonly IBar bar;
public Foo (IBar bar) {
this.bar = bar;
}
}
public class Bar : IBar
{
private readonly IRepository repository;
public Bar(IRepository repository) {
this.repository = repository;
}
}
public class Repository : IRepository
{
private readonly IService service;
public Repository(IService service) {
this.service = service;
}
}
第二步是配置容器:
var container = new UnityContainer();
container.RegisterType<IFoo, Foo>();
container.RegisterType<IBar, Bar>();
container.RegisterType<IRepository, Repository>();
container.RegisterType<IService, Service>();
第三步是解析IFoo
:
IFoo foo = container.Resolve<IFoo>();
现在 Unity 将为您解析整个对象图。
关于c# - 如何使用Unity解决嵌套依赖关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28012300/