autofac / Autofac

An addictive .NET IoC container
https://autofac.org
MIT License
4.44k stars 836 forks source link

Add option to fail on ambiguous service resolution #1404

Closed jvmlet closed 6 months ago

jvmlet commented 6 months ago

Problem Statement

Consider the below registrations :

builder.RegisterType<PostalServiceSender>().As<ISender>();
builder.RegisterType<EmailNotifier>().As<ISender>();
builder.RegisterType<AnotherService>();

class AnotherService{
  public AnotherService(ISender sender){
  }
}

It's impossible to determine which sender will be injected into AnotherService

Desired Solution

Please provider an option to fail the ambiguous dependency resolution when creating the container

tillig commented 6 months ago

It's not impossible to determine - last registration made wins. In your example it'll always be the EmailSender. See documentation here.

This is common/well-known behavior for DI containers. We won't be adding an option to fail if there are multiple potential matches.

jvmlet commented 6 months ago

last registration made wins

Well, if its added by assembly scanning?

About common - spring fails such injection

tillig commented 6 months ago

If you need to control it, don't scan. There are trade offs. For example, in an ASP.NET project the order controllers are registered doesn't matter because you never have to resolve one IController, so scanning is great. In other cases you need to control it, so blanket "scan and register as all implemented interfaces" isn't good. Be more strategic with your registration methods.