希望Autofac不注册任何具有多个实现的接口

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

我们想要遵守以下规则:

  1. 如果一个接口只实现了一次,那么使用builder.RegisterAssemblyTypes自动添加它(见下文)。

  2. 否则,我们需要确保手动编写将决定哪个实现是“默认”实现的规则。

我有以下代码:

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

现在,它正在工作,但它决定了第一个实现是哪个,并将自动创建。 如果我们不手动创建“规则”,我们希望将其设为手动过程并抛出错误。 这可能吗?

你可以这样做:

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

这将注册仅存在单个实现者的所有实现,并忽略具有多个实现的接口,以便您可以手动注册它们。 请注意,我并不认为这在任何方面都是有效的(取决于服务的数量,您可能希望查看缓存实现者)。