想Autofac不注册有多个implentation任何接口 [英] Would like Autofac to not register any interface that has more than one implentation

查看:330
本文介绍了想Autofac不注册有多个implentation任何接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I'm currently testing Autofac for our company.

我们希望有以下规则:

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

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

这篇关于想Autofac不注册有多个implentation任何接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆