使用 Microsoft 的通用主機 DI 和配置,假設我想要兩個不同的物件(可能是不同的,甚至不相關的型別),每個物件都SomeKindOfParameter在其建構式中使用 a 。它們可能需要SomeKindOfParameter使用配置中指定的值(例如 in appsettings.json)注入不同的值。我該怎么做呢?
我知道如何SomeKindOfParameter從配置中獲取不同實體的不同值:
SomeKindOfParameter parameterForTypeX = config.GetSection("ParamForX").Get<SomeKindOfParameter>();
SomeKindOfParameter parameterForTypeY = config.GetSection("ParamForY").Get<SomeKindOfParameter>();
并給出一個單一的 SomeKindOfParameter,我知道我能得到它注射到他們兩個:
SomeKindOfParameter param = ...
services.AddSingleton<SomeKindOfParameter>(param);
services.AddTransient<IX, X>();
services.AddTransient<IY, Y>();
但我怎么能注入parameterForTypeX到X和parameterForTypeY成Y?謝謝。
uj5u.com熱心網友回復:
有幾種方法:
使用泛型
您可以定義從SomeKindOfParameter以下派生的通用助手型別:
class SomeKindOfParameter { }
class SomeKindOfParameter<TCategory> : SomeKindOfParameter
{ }
然后,注入SomeKindOfParameter的TCategory相應給每個服務:
services.AddTransient<SomeKindOfParameter<X>>();
services.AddTransient<IX, X>();
services.AddTransient<SomeKindOfParameter<Y>>();
services.AddTransient<IY, Y>();
class X : IX
{
public X(SomeKindOfParameter<X> parameters)
{
}
}
class Y : IY
{
public Y(SomeKindOfParameter<Y> parameters)
{
}
}
使用ActivatorUtilities類
ActivatorUtilities.CreateInstance 方法允許您直接將引數傳遞給建構式:
services.AddTransient<IX>(serviceProvider =>
{
var config = serviceProvider.GetRequiredService<IConfiguration>();
SomeKindOfParameter parameterForTypeX = config.GetSection("ParamForX")
.Get<SomeKindOfParameter>();
return ActivatorUtilities.CreateInstance<X>(
serviceProvider,
// Parameters not passed through this array will be activated
// from DI container
new object[]
{
parameterForTypeX
});
});
uj5u.com熱心網友回復:
“正確”的方法是使用命名選項,如檔案中所述。
services.Configure<SomeKindOfParameter>("ParamForX",
Configuration.GetSection("SectionForX"));
services.AddTransient<ServiceX>();
public class ServiceX{
public ServiceX(IOptionsSnapshot<SomeKindOfParameter> snapshot){
.... = snapshot.Get("ParamForX");
}
}
雖然服務集合對于每種型別只有一個服務物件,但您可以通過“開放通用”服務添加一個間接層,以隱藏實作細節并為每個服務提供不同的配置實體;
public class Parameter<T> where T : class {
public Parameter(IOptionsSnapshot<SomeKindOfParameter> snapshot){
Value = snapshot.Get(typeof(T).Name);
}
public SomeKindOfParameter Value { get; private set; }
}
public ServiceX(Parameter<ServiceX> p){
.... = p.Value;
}
services.AddSingleton(typeof(Parameter<>));
可能還有一種方法可以動態系結每個配置部分。基于如何.Configure被實作的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347538.html
上一篇:限制長的大小?
