Skip to content

Singleton with multiple interfaces - idiosyncrasies depending on underlying container #23

@szaboopeeter

Description

@szaboopeeter

Feature request

Type

  • - Enhancement - completely new feature
  • - Improvement - make what we have better

Is your feature request related to a problem?

I have web api that was using Unity container with Agoda.IoC on top of it. I was playing around with it, trying to get rid of Unity in favor of the AspNetCore DI. Since we're talking small api, this was fairly easy to do, but some of my integration tests became flaky after this process. Turns out I have a service class, that implements, and is registered into the DI multiple interfaces.

It looks like that when this scenario is used with unity, it will resolve the same instance for each registered interface - this seems to be the desired behavior, since there is even a test for it:

[Test]
public void RegisterByAttribute_WithMultipleAttributes_CanResolveAll()
{
_container.RegisterByAttribute(false, typeof(MultipleAttributes).Assembly);
var result1 = _container.Resolve<IMultipleAttributes1>();
var result2 = _container.Resolve<IMultipleAttributes2>();
Assert.AreEqual(typeof(MultipleAttributes), result1.GetType());
Assert.AreSame(result1, result2);
}

Turns out that my application depends on this behavior, and this works differently if the underlying container is the default asp.net core container. A quick test in MicrosoftExtensionsDependencyInjectionAutowireTests seems to prove this (note that the passing test condition is AreNotSame() in this case):
image

Describe the solution you'd like

Depending whether we want the annotations to behave in the same way regardless of the underlying container, we should either change the default behavior of these implementations to be aligned, or discuss whether this is even a scenario that we want to support in case of .Net DI. If we want to support both methods, we can come up with an "overloaded syntax", something like:

[RegisterSingleton(For = new[]{typeof(IMultipleAttributes1), typeof(IMultipleAttributes2) })]

Additional context

Actually this is a little tricky to do with aspnet di as it is not supported out of box, but not impossible. See aspnet/DependencyInjection#360

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions