如何在方法或属性中使用依赖项注入?

时间:2018-12-14 16:09:42

标签: c# dependency-injection

通常,我在类的构造函数中使用依赖注入。 依赖项已在unity容器中注册,例如:

container.RegisterType<IMyInterface, MyClass>();

但是在一个类中,无法注入构造函数(这是我继承的第三方类,必须使用默认的构造函数(无注入)。

如何在此类中使用MyClass?

谢谢!

2 个答案:

答案 0 :(得分:0)

如果主要约束是调用第3方类的默认构造函数,那么您不能这样做吗?

public class InheritedClass : ThirdPartyClass
{
   private IMyInterface _myInterface;

   // the default ctr of the 3rd party class is still being called
   public InheritedClass(IMyInterface myInterface, string arg) : base(arg)
   {
       _myInterface = myInterface;
   }
}

如果您实际上是说您自己的继承类具有必须使用的某个构造函数,那么为什么不这样做呢?

 public class InheritedClass : ThirdPartyClass
{
   // Constructor that has to be used
    public InheritedClass(string arg) : base(arg)
    {
    }

    // Ctr with DI that also calls the required default ctr - could be used instead..
    public InheritedClass(IMyInterface myInterface, string arg) : this(arg)
    {
        _myInterface = myInterface;
    }
}

如果这些都不适合您的情况,那么您要寻找的是方法注入的概念,例如this one

答案 1 :(得分:0)

我想我不明白这很难。

  

(这是我继承的第三方类,也是默认构造函数(无注入)

假设这是您继承的第三方类:

public abstract MyClassBase
{
  public MyClassBase()
  {
  }

  public abstract void DoSomething();
}

是什么使您无法派生和注入?

public MyClassDerived
{
  private IInjectioned _injection;

  public MyClassDerived(IInjectioned injection)
    // Call default constructor without params
    : base()
  {
    _injection = injection;
  }

  public override void DoSomething()
  {
    _injection.DoSomething();
  }      
}