如果您需要同一接口的不同实例,如何设置 DryIoc 容器?

How is a DryIoc container setup if you need different instances of same interface?

我正在尝试将 DryIoc 与 .NET Web API 2 站点一起使用来创建我的控制器。我有一种情况,我的控制器需要一个处理器,而处理器需要两个存储实例 class。这是基础知识:

public interface IStorage
{
    IEnumerable<string> List();
    void Add(string file);
    void Remove(string file);
}

public class FileSystemStorage : IStorage
{
    // Implement to store on file system.
}

public class S3Storage : IStorage
{
    // Implement to store in S3 bucket.
}

public interface IProcessor
{ 
    void Process();
}

public class Processor(IStorage sourceStorage, IStorage targetStorage)
{ // Implement a process that interacts with both storages }

public class ProcessController : ApiController
{
    private readonly IProcessor processor;
    public ProcessController(IProcessor processor)
    {
        this.processor = processor;
    }
}

所以,我需要让我的 IOC 容器 (DryIoc) 为接口 IStorage 使用两个不同的 classes。所以,我想要的是像这样设置 IOC:

var sourceStorage = new FileSystemStorage();
var targetStorage = new S3Storage();
var processor = new Processor(sourceStorage, targetStorage);
// And then have DryIoc dependency resolver create 
// controller with this processor.

但是,正常的注册方式是行不通的:

var c = new Container().WithWebApi(config);

// Need two different implementations...
c.Register<IStorage, ???>();

// And even if I had two instances, how would 
// the processor know which one to use for what parameter?
c.Register<IProcessor, Processor>();

我是依赖注入容器的新手,大多数文档都非常抽象;我不是在摸索他们。这是怎么做到的?

直接的方式是用不同的key识别不同存储实现的注册,并指示processor what is what:

c.Register<IStorage, Foo>(serviceKey: "in");
c.Register<IStorage, Bar>(serviceKey: "out");
c.Register<IProcessor, Processor>(made: Parameters.Of
    .Name("source", serviceKey: "in")
    .Name("target", serviceKey: "out"));

问题是,这是一种脆弱的方法,因为更改参数名称会破坏设置。

可能是,你需要回顾一下为什么你有两个相同的接口参数,但职责不同,并且更恰当地区分它们的作用absractions/interfaces。