StructureMap - Inclusion of dependency in base class?

In my domain, I have several โ€œprocessorโ€ classes that occupy the bulk of the business logic. Using StructureMap with default conventions, I insert repositories into these classes for my various IOs (databases, file systems, etc.). For instance:

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 would like to get for all processors, so I made the base class as follows:

 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 of them, saying that there is no constructor for BaseProcessor that accepts null arguments.

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

+4
source share
2 answers

Not. This is a C # language requirement, not a limitation of StructureMap. A derived class must pass values โ€‹โ€‹to its base constructors. If you use the base class solely for processing a regular service, you get nothing. Just put the shared service in every class that it needs โ€” your IoC tool will take care of that โ€” what harm?

+4
source

What you want is an injection of properties. It is normal for a base class to have a public property with the dependency introduced, because you will never use derived classes as concrete instances of the base class โ€” you should always use the interfaces of your derived classes.

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

+2
source

Source: https://habr.com/ru/post/1311106/


All Articles