0

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 ?

3
  • Which DI container you are using? Commented Sep 28, 2018 at 6:09
  • ASP.NET Core default DI container Commented Sep 28, 2018 at 6:11
  • 1
    Please post a MCVE and the full stack trace. Commented Sep 29, 2018 at 9:36

1 Answer 1

2

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>()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.