开发者

StructureMap - Injecting a dependency into a base class?

开发者 https://www.devze.com 2023-01-01 11:44 出处:网络
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

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?


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?


What you want is property injection. It's okay for the base class to have a public property with the dependency injected because you will never use the derived classes as concrete instances of the base class - you will (should) always be using the interfaces of your derived classes.

The answer here is to avoid this glaring weakness in constructor injection and use property injection on your base class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号