想Autofac不注册有多个implentation任何接口多个、接口、Autofac、implentation

2023-09-05 23:25:14 作者:风居住的街道

所以,我目前正在测试Autofac我们公司。

So I'm currently testing Autofac for our company.

我们希望有以下规则:

如果一个接口已经执行一次,然后自动使用builder.RegisterAssemblyTypes(见下文)。添加它

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

否则,我们需要确保手工编写,这将决定规则,实行的是默认的实现。

Otherwise, we need to make sure to manually write the rule that will decide which implementation is the 'default' implementation.

我有以下的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?

推荐答案

您可以做这样的事情:

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