我有两个相互依赖的类,我希望Autofac实例化。基本上,父级需要对子级的引用,并且子级需要对服务的引用,在这种情况下父级实际执行。
public class Parent : ISomeService
{
private IChild m_child;
public Parent(IChild child)
{
m_child = child; // problem: need to pass "this" to child constructor
}
}
public class Child : IChild
{
public Child(ISomeService someService)
{
// ...store and/or use the service...
}
}
有什么想法吗?
答案 0 :(得分:0)
我使用parameterized instantiation找到了一个相当优雅的解决方案。它允许孩子对ISomeService
的依赖关系使用现有对象(Parent
实例)解决,而不会引入任何混乱的生命周期问题(据我所知):
public class Parent : ISomeService
{
private IChild m_child;
public Parent(Func<ISomeService, IChild> childFactory)
{
m_child = childFactory(this);
}
}
public class Child : IChild
{
public Child(ISomeService someService)
{
// ...store and/or use the service...
}
}
// Registration looks like this:
builder.RegisterType<Parent>(); // registered as self, NOT as ISomeService
builder.RegisterType<Child>().AsImplementedInterfaces();
像魅力一样工作。 :)