Simple Injector可以使用不同的构造函数参数注册相同类型的多个实例吗?

时间:2014-05-20 20:28:26

标签: c# dependency-injection simple-injector

我正在调查使用Simple Injector作为我的依赖注入器。我暂时将使用MemoryCache类的不同实例作为注入依赖项:

public class WorkflowRegistrationService : IWorkflowRegistrationService
{
    public WorkflowRegistrationService( MemoryCache cache ) {}
}

public class MigrationRegistrationService : IMigrationRegistrationService
{
    public MigrationRegistrationService( MemoryCache cache ) {}
}

如果我正在修改课程,我会执行以下操作,为每个服务创建不同的缓存:

var workflowRegistrationCache = new MemoryCache("workflow");
var migrationRegistrationCache = new MemoryCache("migration");

如何使用Simple Injector完成这项工作?基本上,我需要告诉它在注入特定类型时使用特定实例。

1 个答案:

答案 0 :(得分:4)

最简单的方法可能如下:

var workflowRegistrationCache = new MemoryCache("workflow");

container.Register<IWorkflowRegistrationService>(
    () => new WorkflowRegistrationService(workflowRegistrationCache));

var migrationRegistrationCache = new MemoryCache("migration");

container.Register<IMigrationRegistrationService>(
    () => new MigrationRegistrationService(
        container.GetInstance<ISomeService>(),
        migrationRegistrationCache));

另一个选择是context bases injection。如果您使用here给出的代码段,则可以执行以下注册:

var workflowRegistrationCache = new MemoryCache("workflow");
var migrationRegistrationCache = new MemoryCache("migration");

container.RegisterWithContext<MemoryCache>(context =>
{
   return context.ServiceType == typeof(IWorkflowRegistrationService)
       ? workflowRegistrationCache 
       : migrationRegistrationCache;
});

container.Register<IWorkflowRegistrationService, WorkflowRegistrationService>();
container.Register<IMigrationRegistrationService, MigrationRegistrationService>();

这允许您让容器自动连接WorkflowRegistrationServiceMigrationRegistrationService,同时也可以轻松注入其他依赖项。

但请注意,您的设计存在一些歧义,您可能希望解决此问题。 This Stackoverflow answer详细介绍了这一点。