简体   繁体   中英

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

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

when i request specific implementation serviceAccessor(MessageType.Sms) throws an exception

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)

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. Maybe it's an issue of the latest if .Net Core I faced the same here.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM