我们如何从依赖类中访问注入器对象?

时间:2015-05-04 08:29:53

标签: c# inversion-of-control autofac

使用Autofac,我们如何从依赖类中访问激活器类?

例如,我们有两个类AB,类A会注入B。所以我想从A的构造函数访问B对象的引用:

public class A
{
   private readonly B _b;
   public A(B b)
   {
      _b = b;
   }
}

public class B
{
   public B( ... )
   {
       //  in here i want to access to the reference of
       //  the object which injects this class,
       //  (which in this example is the 'A')

   }
}

感谢。

1 个答案:

答案 0 :(得分:1)

如果你需要,你应该考虑重新设计 A ,循环依赖将使你的生活更加困难。 SRP原则是否得到尊重?将 A 拆分为不同的类可能是解决方案。

顺便说一句,如果您真的想这样做,我强烈反对,您可以使用Lazy<A>

class A
{
    private readonly B _b;
    public A(B b)
    {
        _b = b;
    }
}

class B
{
    public B(Lazy<A> a)
    {
        this._a = a;
    }

    private readonly Lazy<A> _a;
}

当然,您无法在 B 的构造函数中访问 A 的值,但您将能够访问 A on B 方法。