I would like Autofac not to register an interface with more than one implementation

I am currently testing Autofac for our company.

We would like to have the following rules:

  1. If the interface was implemented only once, add it automatically using builder.RegisterAssemblyTypes (see below).

  2. Otherwise, we must make sure to manually write a rule that decides which implementation is the default implementation.

I have the following code:

var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly
    .Load("Lunch.Service")).As(t => t.GetInterfaces()[0]);
builder.RegisterType<ConsoleLoggerService>()
    .As<ILoggerService>().SingleInstance();
builder.RegisterModule(new DestinationModule());
builder.RegisterType<TransportationService>()
    .As<ITransportationService>().PropertiesAutowired();

Right now, it works, but it decides which first implementation will automatically create it. We would like to make this a manual process and give an error if we do not create a “rule” manually. Is it possible?

+3
source share
1

- :

cb.RegisterAssemblyTypes(assembly).Where(type =>
{
    var implementations = type.GetInterfaces();

    if (implementations.Length > 0)
    {
        var iface = implementations[0];

        var implementers =
            from t in assembly.GetTypes()
            where t.GetInterfaces().Contains(iface)
            select t;

        return implementers.Count() == 1;
    }

    return false;
})
.As(t => t.GetInterfaces()[0]);

, , , . , , ( , , , , ).

+1

All Articles