Additional constructor insertion arguments with .NET Core

In some IoC containers, there may be arguments in the constructor that cannot be executed by the container. Is this possible with the Microsoft.Extensions.DependencyInjection and IServiceProvider ? If not, what is a clean solution to this kind of problem?

For instance:

 class InContainer { public InContainer(NotInContainer dependency) { ... } } class Consumer { public Consumer(IServiceProvider serviceProvider) { NotInContainer currentDependency = ... // from some other source // passing the anonymous object here is not supported, // but I would like to InContainer = serviceProvider.GetService<InContainer>( new { dependency = currentDependency } ); } } 
+5
source share
2 answers

Usually I create a factory manually in this case.

 public class TheFactory { public TheFactory( SomeType fromContainer ) { _fromContainer = fromContainer; } public IProduct Create( SomeOtherType notFromContainer ) => new TheProduct( _fromContainer, notFromContainer ); private readonly SomeType _fromContainer; private class TheProduct : IProduct { // ... } } 

If you need dependencies on each product from the container, factory Create must resolve them. Or, in the case of, for example, a unit, factory gets Func from the container.

+2
source

In your example, you provide the serviceProvider runtime currentDependency . Application components should not require data at run time, as described here . The solution is to reorganize your design as described in this article.

About additional arguments:

The fact that some DI containers support optional arguments prevents them from using them. In fact, the arguments of the injection constructor should never be extra.

As explained in this article:

An optional dependency implies that the reference to the dependency will be null if it is not provided. Null references complicate the code because they require specific logic for the null case. Instead of passing a null reference, the caller can insert an implementation without any behavior, that is, an implementation of a null object template.

If not, what is a clean solution to this kind of problem?

As indicated, the Null Object pattern is a solution for this even when using a DI container that actually supports optional constructor dependencies.

0
source

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


All Articles