如何使用Autofac创建相互依赖的组件

时间:2016-10-04 17:21:45

标签: c# 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...
    }
}

有什么想法吗?

1 个答案:

答案 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();

像魅力一样工作。 :)