Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispose being called multiple times by Microsoft DependencyInjection

I'm registering a class twice but with different contracts.

services
    .AddSingleton<MyClass>()
    .AddSingleton<IHostedService>(sp => sp.GetService<MyClass>());

The class also implements IDisposable which means the Dispose method will be called on application shutdown. But since it's registered twice, it will be called twice.

Autofac has two ways of solving this:

builder.RegisterType<MyClass>().AsSelf().As<IHostedService>();
//or
builder.RegisterType<MyClass>().AsSelf();
builder.Register(ctx => ctx.Resolve<MyClass>()).As<IHostedService>().ExternallyOwned();

But can't seem to do any of those with Microsoft DependencyInjection in ASP.NET Core. Is there a way to solve it?

like image 709
Allrameest Avatar asked Oct 14 '25 14:10

Allrameest


1 Answers

Dispose method will be called on application shutdown. But since it's registered twice, it will be called twice. . . .Is there a way to solve it?

Yes. The problem is in your IDisposable implementation:

If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.

IDisposable.Dispose

like image 99
David Browne - Microsoft Avatar answered Oct 17 '25 03:10

David Browne - Microsoft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!