views:

83

answers:

1

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?

+1  A: 

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?

Joshua Flanagan
I guess there's no real harm, I was just trying to consolidate things a little bit. Makes the code a little cleaner is all.The trade-off now is to either include the common dependencies in every class' constructor, or to manually instantiate the dependency in the base class (calling ObjectFactory.GetInstance() instead of expecting a constructor argument). I guess it's time to abstract-out my IoC container, making that second option a little more comfortable :)
David
Nooooo... that would be going down a bad path. Forcing a service location just because you are uncomfortable with the number of constructor parameters? Please don't. If you have a number of common dependencies (not just the one), then maybe you have some common functionality that should be factored out into a another service. That service would take in the multiple dependencies and perform the work that requires them. You would then inject that service into the other constructors. That's what is mean by "favor composition over inheritance".
Joshua Flanagan