Skip to content

Dispose called multiple time for same instance when registering service for multiple interfaces #1155

@pihalve

Description

@pihalve

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:

  1. Create a class called Foo that implements two interfaces IFoo and IBar. Additionally, have Foo implement IDisposable.

  2. 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

  3. 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

  4. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions