.NET Core的可选构造函数注入参数

Dan*_*ite 8 c# dependency-injection .net-core

在某些IoC容器中,可能在构造函数中具有容器无法实现的参数.这可能与Microsoft.Extensions.DependencyInjection图书馆和IServiceProvider?如果没有,这种问题的清洁解决方案是什么?

例如:

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 }
         );
    }
}
Run Code Online (Sandbox Code Playgroud)

Hau*_*ger 3

通常,在这种情况下我会手动创建一个工厂。

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
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要容器中的每个产品依赖项,工厂Create必须解决它们。或者,在统一的情况下,工厂Func从容器中获取 a。