Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 简单注入器能否使用不同的构造函数参数注册相同类型的多个实例?_C#_Dependency Injection_Simple Injector - Fatal编程技术网

C# 简单注入器能否使用不同的构造函数参数注册相同类型的多个实例?

C# 简单注入器能否使用不同的构造函数参数注册相同类型的多个实例?,c#,dependency-injection,simple-injector,C#,Dependency Injection,Simple Injector,我正在研究使用Simple Injector作为依赖项Injector。我暂时将使用MemoryCache类的不同实例作为注入依赖项: public class WorkflowRegistrationService : IWorkflowRegistrationService { public WorkflowRegistrationService( MemoryCache cache ) {} } public class MigrationRegistrationService

我正在研究使用Simple Injector作为依赖项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");

如何使用简单的喷油器进行此操作?本质上,我需要告诉它在注入特定类型时使用特定实例。

最简单的方法可能如下所示:

var workflowRegistrationCache=newmemorycache(“工作流”);
集装箱。登记(
()=>新的WorkflowRegistrationService(workflowRegistrationCache));
var migrationRegistrationCache=新内存缓存(“迁移”);
集装箱。登记(
()=>新的迁移注册服务(
container.GetInstance(),
migrationRegistrationCache);
另一个选择是这样做。如果使用给定的代码段,则可以执行以下注册:

var workflowRegistrationCache=newmemorycache(“工作流”);
var migrationRegistrationCache=新内存缓存(“迁移”);
container.RegisterWithContext(context=>
{
return context.ServiceType==typeof(IWorkflowRegistrationService)
?workflowRegistrationCache
:migrationRegistrationCache;
});
container.Register();
container.Register();
这允许容器自动连接
WorkflowRegistrationService
MigrationRegistrationService
,也允许轻松注入其他依赖项


但是请注意,您的设计中存在一些模糊性,您可能希望解决这个问题。关于这方面的更多细节。

好的,现在让我们来看一看,如果还有其他正常的依赖项:publicWorkflowRegistrationService(IRepository repository,MemoryCache){},该怎么办。我希望对IRepository进行正常的解析,但类似于您建议的MemoryCache。谢谢更新。这回答了我的问题。然而,关于设计模糊性(和链接)的评论让我思考得更清楚,我意识到最好为每个缓存提供接口,因为这将清楚地表明实际情况,并将其与任何特定实现分离。我想我一开始是因为MemoryCache没有我可以使用的接口。我明白了,额外的接口提供了编写适配器的保证。谢谢