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??
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.
class Base
{
[Dependency]
public IDep Dep { get; set; }
}
class Base
{
private IDep dep;
[InjectionMethod]
public void Initialize(IDep dep)
{
this.dep = dep;
}
}
Please note: