[英]DI multiple implementation on single interface
I have multiple concrete implementations on a single interface. 我在一个界面上有多个具体实现。 I have registered that in to ASP.NET core DI as below
我已将其注册到ASP.NET Core DI中,如下所示
services.AddTransient<EmailService>();
services.AddTransient<SmsService>();
services.AddTransient<Func<MessageType, IMessageService>>(serviceProvider => key =>
{
switch (key)
{
case MessageType.Email:
return serviceProvider.GetService<EmailService>();
case MessageType.Sms:
return serviceProvider.GetService<SmsService>();
default:
throw new KeyNotFoundException();
}
});
then i inject Func<MessageType, IMessageService> serviceAccessor
to constructor 然后我将
Func<MessageType, IMessageService> serviceAccessor
注入构造函数
when i request specific implementation serviceAccessor(MessageType.Sms)
throws an exception 当我请求特定的实现时
serviceAccessor(MessageType.Sms)
引发异常
Activated Event Time Duration Thread Exception thrown: 'System.ObjectDisposedException' in Microsoft.Extensions.DependencyInjection.dll ("Cannot access a disposed object.") Exception thrown: 'System.ObjectDisposedException' in Microsoft.Extensions.DependencyInjection.dll ("Cannot access a disposed object.") Hyperlink: Activate Historical Debugging 8.97s [428] WorkPool-Session#2:Connection(3a5aaef7-e40f-4607-9d12-eacbd0dd5f6d,amqp://localhost:5672)
引发的激活事件持续时间线程异常:Microsoft.Extensions.DependencyInjection.dll中抛出“ System.ObjectDisposedException”(“无法访问已处置的对象。”)异常抛出:Microsoft.Extensions.DependencyInjection.dll中出现“ System.ObjectDisposedException”(“访问已处置的对象。”)超链接:激活历史调试8.97s [428] WorkPool-Session#2:Connection(3a5aaef7-e40f-4607-9d12-eacbd0dd5f6d,amqp:// localhost:5672)
what was the issue ? 这是什么问题?
Problem becuase in your implementation class was call to the IServiceProvider which will be dispose after the factory of the of the DI. 由于您的实现类中的问题是调用了IServiceProvider,该IServiceProvider将在DI的工厂后处置。 Maybe it's an issue of the latest if .Net Core I faced the same here.
如果.Net Core在这里遇到相同问题,也许这是最新的问题。
And for the multiple implementations of the interface. 并用于接口的多种实现。 I think better will be
我认为会更好
Interface IMessage<T>
Class MailMessage : IMessage<MessageType>
Services.AddTransient<IMessage<MessageType>, MailMessage>()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.