Paul
Paul

Reputation: 1757

dependency injection into a set of classes

I have in mind a set of classes which all will need to be instantiated with some dependency object during construction. Consider these classes:

class A { A(IDependency dep) {...} }  
class B { A(IDependency dep) {...} }  
class C { A(IDependency dep) {...} }  
class D { A(IDependency dep) {...} }  

I want the DI to take place in the constructor, and obviously I want classes A,B,C,D to inherit from some abstract class or implement the same interface.

Problem: I can't include the constructor in an interface or an abstract class.

What to do? Inherit from a non-abstract base class? The base class doesn't have a real meaning. Use factory methods? Never really liked them...

Any suggestions?

Upvotes: 0

Views: 412

Answers (2)

Moo-Juice
Moo-Juice

Reputation: 38825

Of course you can have a ctor in an abstract class.

public interface IDependency
{
}

public abstract class A
{
    protected IDependency _dep;

    protected A(IDependency dep)
    {
        _dep = dep;
    }
}

public class B : A
{
    public B(IDependency dep) : base(dep)

    {
    }
}

Upvotes: 3

Adam
Adam

Reputation: 629

You CAN include a constructor in the abstract class and that's how I usually do it. Or you could use property injection instead of constructor which you would be able to include in the interface.

Upvotes: 0

Related Questions