Would like Autofac to not register any interface that has more than one implementation

偶尔善良 提交于 2020-02-03 10:10:27

问题


I'm currently testing Autofac for our company.

We'd like to have the following rules:

  1. If an interface has been implemented only once, then add it automatically using the builder.RegisterAssemblyTypes (see below).

  2. Otherwise, we need to make sure to manually write the rule that will decide 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's working, but it decides which the first implementation is and will automatically create that. We'd like to make that a manual process and have an error thrown if we don't manually create the 'rule'. Is this possible?


回答1:


You could do something like this:

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]);

This will register all implementations where only a single implementer exists, and ignore interfaces with multiple implementations so you can register them manually. Note that I don't claim this is efficient in any way (depending on the number of services, you may want to look at caching implementers for example).



来源:https://stackoverflow.com/questions/10486342/would-like-autofac-to-not-register-any-interface-that-has-more-than-one-implemen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!