Should infrastructure dependencies be built in?

With infrastructure elements like logs, security, configuration, etc., should these things really be entered for every class they need, or should they be entered in the service locator, and then the classes can use the service locator to resolve the dependencies (or any other mechanism)?

It just looks very funny when all classes having 10 parameters satisfy dependencies via DI. Its code smell is IMO. I can understand things like repositories or service proxies / connectors, but not logging.

+4
source share
3 answers

It all depends on where you draw the line between the infrastructure and the rest of the code. Do you think connecting to a database is an infrastructure? I do not do this.

Adding properties is the smell of code because it hides dependencies and classes are not initialized properly when the constructor runs. Use it only to solve cyclic dependencies.

For a specific case of logging, I use singleton to get the logger.

Normaly I would agree with you at AOP, but I am not a fan of AOP frameworks, and the team does not understand the concept of AOP. They barely understand the concepts of IoC.

You can find a useful IoC introduction .

+2
source

there are several options.

  • use the injection property and set the default value to ctor. eg

    class foo { public ILogger Logger {get;set;} public foo() { Logger = NullLogger.Instance; } } 
  • use an AOP approach. using a dynamic proxy, you can exchange public calls with logging operators, but logging is never entered in the component itself. See Castle.DynamicProxy or the custom .Net attribute for more ideas on this approach.

the question then becomes, why are so many infrastructure problems injected into the component? what you describe are considered cross-cutting problems, and usually this is handled through some for AOP (aspect-oriented programming), so there is not much duplication in the main system.

+4
source

As for logging, just use NLog (or your favorite journal) and do it. If you are not in a really strange scenario, there is no reason to abstract and / or enter your registrar.

As for the configuration - only a few classes should be consumers of the configuration, so this should not cause the constructor to bloat. See also this question for a good discussion of configuration and DI.

Regarding security - again, I think that only a few classes should be consumers of security dependencies. If many classes relate to security, you may need to rethink your design.

In the general case, if a class has too many constructor parameters, this is probably because it does too much, regardless of whether the dependencies are infrastructural.

+1
source

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


All Articles