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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With