[英]Multiple dependency injections for same class C# and .NET Core
我有一個界面
public interface ITest
{
void SayHello();
}
它被實現為
public class Test : ITest
{
Test(string type)
{
// Do Something with type
}
public void SayHello()
{
//
}
}
將其在 DI 中注冊為:
services.AddScoped<ITest, Test>();
我需要創建兩個具有這些條件的實例:
Test t1 = new Test("ABC");
Test t2 = new Test("XYZ");
如何使用 DI 實現這一目標?
考慮到這個確切的用例,DI 提供了以下方法: ActivatorUtilities.CreateInstance
(注意使用ITest
vs Test
)
Test t1 =
ActivatorUtilities
.CreateInstance<Test>("ABC");
Test t2 =
ActivatorUtilities
.CreateInstance<Test>("XYZ");
有幾個選項可以實現它。
創建一個工廠來生成您需要的實例:
public TestFactory : ITestFactory
{
public ITest Create(string type)
{
return new Test(type);
}
}
只注冊工廠
services.AddScoped<ITestFactory, TestFactory>();
優點是您擁有可以模擬的ITestFactory
的單段代碼以及如何創建實例和創建哪個實例的整個邏輯。
將它們全部注冊為ITest
services.AddScoped<ITest>(sp => new Test("ABC"));
services.AddScoped<ITest>(sp => new Test("XYZ"));
...然后在這樣的類中使用它:
public class Consumer
{
public Consumer(IEnumerable<ITest> testInstances)
{
// This is working great if it does not matter what the instance is and you just need to use all of them.
}
}
...或者只是使用ActivatorUtilities
,這是一種直接從IServiceProvider
創建實例的方法, 請參閱文檔或其他SO 問題
var serviceProvider = <yourserviceprovider>;
var test1 = ActivatorUtilities.CreateInstance<Test>(sp, "ABC");
var test2 = ActivatorUtilities.CreateInstance<Test>(sp, "XYZ");
但就像它也寫在你的問題的評論中一樣,它真的取決於你想對這兩個實例做什么以及你從哪里獲得string type
。
您還可以結合選項 1 和 2 執行更高級的方法,但因此需要更好地描述您的問題和用法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.