簡體   English   中英

Simple Injector可以使用不同的構造函數參數注冊相同類型的多個實例嗎?

[英]Can Simple Injector register multiple instances of same type using different constructor parameters?

我正在研究使用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完成這項工作? 基本上,我需要告訴它在注入特定類型時使用特定實例。

最簡單的方法可能如下:

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));

另一種選擇是進行上下文基礎注入 如果您使用此處提供的代碼段,則可以執行以下注冊:

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 ,從而也可以輕松注入其他依賴項。

但請注意,您的設計存在一些歧義,您可能希望解決此問題。 此Stackoverflow答案詳細介紹了這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM