[英]Registering a named type with autofac and using the name for string parameter
我有以下注冊信息(請注意,我尚未完成此代碼,所以它甚至可能無法按預期工作):
builder.RegisterType<SimpleInMemoryChannel>()
.Named<IChannel>("ErrorChannel")
.WithParameter(new NamedParameter("channelName", "ErrorChannel"));
builder.RegisterType<SimpleInMemoryChannel>()
.Named<IChannel>("RequestCbrInput")
.WithParameter(new NamedParameter("channelName", "RequestCbrInput"));
// Constructor: public SimpleInMemoryChannel(string channelName)
如您所見,我正在嘗試將注冊對象的名稱用作channelName值。 該代碼有點冗長。 有什么辦法可以讓我自動進行分配? 例如,我只想寫:
builder.RegisterType<SimpleInMemoryChannel>()
.Named<IChannel>("ErrorChannel");
builder.RegisterType<SimpleInMemoryChannel>()
.Named<IChannel>("RequestCbrInput");
並自動設置channelName。
默認功能沒有任何東西可以允許這種情況發生。 您將需要自定義注冊,或使用工廠進行解析。 最簡單的解決方案是您在注釋中提到的解決方案-添加用於注冊頻道的幫助程序功能-這樣,您仍然可以使用默認解析過程。
使用RegisterChannel
方法可能是更優雅的解決方案。
順便說一句,如果您沒有這種方法,可以使用自定義模塊:
public class NamedParameterModule<TServiceType> : Module
{
private readonly string _parameterName;
public NamedParameterModule(String parameterName)
{
this._parameterName = parameterName;
}
protected override void AttachToComponentRegistration(
IComponentRegistry componentRegistry, IComponentRegistration registration)
{
KeyedService keyedService = registration.Services
.OfType<KeyedService>()
.FirstOrDefault(ks => ks.ServiceType == typeof(TServiceType));
if (keyedService != null)
{
registration.Preparing += (sender, e) =>
{
e.Parameters = e.Parameters.Concat(new Parameter[] {
new NamedParameter(this._parameterName, keyedService.ServiceKey)
});
};
}
base.AttachToComponentRegistration(componentRegistry, registration);
}
}
並使用builder.RegisterModule(new NamedParameterModule<IFoo>("channelName"));
這是dotnetfiddle的實時示例: https ://dotnetfiddle.net/MPfMup。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.