如何使用 Autofac 创建相互依赖的组件
How to create mutually dependent components using Autofac
我有两个相互依赖的 类,我希望 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...
}
}
有什么想法吗?
我使用 parameterized instantiation 找到了一个相当优雅的解决方案。它允许使用现有的 object(Parent
实例)解决 child 对 ISomeService
的依赖,而不会引入任何混乱的生命周期问题(据我所知) ):
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();
很有魅力。 :)
我有两个相互依赖的 类,我希望 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...
}
}
有什么想法吗?
我使用 parameterized instantiation 找到了一个相当优雅的解决方案。它允许使用现有的 object(Parent
实例)解决 child 对 ISomeService
的依赖,而不会引入任何混乱的生命周期问题(据我所知) ):
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();
很有魅力。 :)