我正在尝试将 DryIoc 与 .NET Web API 2 站点一起使用来创建我的控制器。我有一种情况,我的控制器需要一个处理器,而处理器需要一个存储类的两个实例。以下是基础知识:
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
。所以,我想要为这样的事情设置 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>();
我是依赖注入容器的新手,大多数文档都非常抽象;我不是在摸索他们。这是怎么做到的?