Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StructureMap - Injecting a dependency into a base class?

In my domain I have a handful of "processor" classes which hold the bulk of the business logic. Using StructureMap with default conventions, I inject repositories into those classes for their various IO (databases, file system, etc.). For example:

public interface IHelloWorldProcessor
{
    string HelloWorld();
}
public class HelloWorldProcessor : IHelloWorldProcessor
{
    private IDBRepository _dbRepository;
    public HelloWorldProcessor(IDBRepository dbRepository)
    {
        _dbRepository = dbrepository;
    }
    public string HelloWorld(){ return _dbRepository.GetHelloWorld(); }
}

Now, there are some repositories that I'd like to be available to all processors, so I made a base class like this:

public class BaseProcessor
{
    protected ICommonRepository _commonRepository;
    public BaseProcessor(ICommonRepository commonRepository)
    {
        _commonRepository = commonRepository;
    }
}

But when my other processors inherit from it, I get a compiler error on each one saying that there's no constructor for BaseProcessor which takes zero arguments.

Is there a way to do what I'm trying to do here? That is, to have common dependencies injected into a base class that my other classes can use without having to write the injections into each one?

like image 687
David Avatar asked May 27 '10 15:05

David


1 Answers

No. That is a C# language requirement, not a StructureMap limitation. A derived class must pass values to its base constructors. If you are using the base class solely to handle injecting a common service, you are not gaining anything. Just put the common service on each class that needs it - your IoC tool will take care of it - whats the harm?

like image 79
Joshua Flanagan Avatar answered Oct 22 '22 06:10

Joshua Flanagan