Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicitly injecting dependency in Base class while derived class is resolved through Unity

I have a base Class Base having dependecy Dep and default and Injection Constructor-

Class Base : IBase
 {

    public IDep Dep { get; set; }

    public Base()
    {
        Console.WriteLine("Default Constructor Base ");
    }

    [InjectionConstructor]
    public Base(IDep dep)
    {
        Console.WriteLine("Injection Constructor Base ");
        Dep = dep;            
    }
}

I thought that Dependency dep should get injected automatically(through Constructor Injection) when derived class is resolved.

But this doesnt seem to work when I derive a class from it and Resolve that class, Instead a default Constructor of Base being called.

I can only get this to work when I explicitly call the constructor from the Derived Class.

class Derived : Base
{

    public Derived ()
    {
        Console.WriteLine("Default Constructor Derived ");
    }

    public Derived (IDep dep) : base(dep1)
    {
        Console.WriteLine("Injection Constructor Derived ");            
    }
}

Does unity provide any direct way to implicitly call the injection Constructor of base class (not by explicit Construtor call)? If not, Is there any reason that why unity container is not doing by itself??

like image 242
Rajat Srivastava Avatar asked Sep 11 '14 05:09

Rajat Srivastava


1 Answers

No, unity is unable to do so. Actually, there's not a single container who can do so. A constructor is there to instantiate a class. If you call two constructors, you'll end up with two instances. If the base class is abstract, you couldn't even call its constructor (except derived constructors as you know).

So by limitations of C#.net, if you want to use constructor injection, it will only work if you explicitly inject the value into the Derived constructor which calls the non-default Base constructor.

However, you might choose to use Property or Method injection instead. With these you don't have to add the dependency to every constructor of a derived class.

Property Injection:

class Base
{
    [Dependency]
    public IDep Dep { get; set; }
} 

Method Injection:

class Base
{
     private IDep dep;

     [InjectionMethod]
     public void Initialize(IDep dep)
     {
         this.dep = dep;
     }
}

Please note:

  • The object is instantiated (ctor injection) before method / property injection is performed
  • It might be adequate to adapt the design to not require a base class, see Composition over Inheritance
like image 74
BatteryBackupUnit Avatar answered Oct 27 '22 19:10

BatteryBackupUnit