希望Autofac不注册具有多个实现的任何接口 [英] Would like Autofac to not register any interface that has more than one implementation

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

问题描述

我目前正在为我们的公司测试Autofac.

I'm currently testing Autofac for our company.

我们希望遵循以下规则:

We'd like to have the following rules:

  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.

我有以下代码:

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不注册具有多个实现的任何接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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