-
Notifications
You must be signed in to change notification settings - Fork 840
Description
Describe the bug
I actually don't know if it's a bug or by design, but to me it looks like a bug. Basically, what I'm trying to do is registering same singleton instance as multiple interfaces. I know that there is not explicit support for this in M.E.DI, but it can be sort of accomplished by doing this:
services.AddSingleton<Foo>(); // We must explicitly register Foo
services.AddSingleton<IFoo>(x => x.GetRequiredService<Foo>()); // Forward requests to Foo
services.AddSingleton<IBar>(x => x.GetRequiredService<Foo>()); // Forward requests to Foo
The same instance of Foo can now be injected as both IFoo and IBar. However, the problem is, that if Foo implements IDisposable, then Dispose will be called for all three resolved registrations, i.e. for Foo, IFoo and IBar.
To Reproduce
Steps to reproduce the behavior:
-
Create a class called Foo that implements two interfaces IFoo and IBar. Additionally, have Foo implement IDisposable.
-
Do registrations like this:
services.AddSingleton(); // We must explicitly register Foo
services.AddSingleton(x => x.GetRequiredService()); // Forward requests to Foo
services.AddSingleton(x => x.GetRequiredService()); // Forward requests to Foo -
Resolve the registrations:
var foo1 = provider.GetService(); // An instance of Foo
var foo2 = provider.GetService(); // The instance of Foo
var foo3 = provider.GetService(); // The instance of Foo -
Check that Dispose is called when "shutting down". It will be called three times.
Expected behavior
Since there is only one instance, I expect Dipose to be called only once.