您必须将Autofac视为一种Dictionary<IComponentRegistration>
. 注册可以绑定到类型或委托或具有配置行为的所有其他内容。
通过注册两次Type您将拥有两个 distinct IComponentRegistration
,在您的情况下,注册将是相似的。如果您查看以下差异,您会发现您将有两个不同的注册,它们使用相同Type
但具有不同的配置。
builder.RegisterType<A>().WithConstrusctorArgument("param1", "x");
builder.RegisterType<A>().WithConstrusctorArgument("param1", "y");
在这种情况下,解析IEnumerable<A>
将为您提供两个不同的实例,A
并且确实有意义。
有没有办法强制枚举为每个实现提供一个项目
我不建议这样做。最好重构您的应用程序以不允许这种情况,如果您需要删除Autofac中的很多好东西。如果你有一个Type
可能在多个模块中注册Type
的,那么在主模块中注册它可能是有意义的。
顺便说一句,如果你真的想这样做,你将不得不找到一种方法来区分你的容器的所有注册。IEnumerable<>
然后您可以通过实现自己的来覆盖默认实现IRegistrationSource
,以下示例将为您提供每种类型的唯一注册。
class CustomEnumerableRegistrationSource : IRegistrationSource
{
public Boolean IsAdapterForIndividualComponents
{
get
{
return false;
}
}
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
IServiceWithType typedService = service as IServiceWithType;
if (typedService == null)
{
return Enumerable.Empty<IComponentRegistration>();
}
if (!(typedService.ServiceType.IsGenericType && typedService.ServiceType.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
{
return Enumerable.Empty<IComponentRegistration>();
}
Type elementType = typedService.ServiceType.GetGenericArguments()[0];
Service elementService = typedService.ChangeType(elementType);
Type collectionType = typeof(List<>).MakeGenericType(elementType);
IComponentRegistration registration = RegistrationBuilder.ForDelegate(collectionType, (c, p) =>
{
IEnumerable<IComponentRegistration> registrations = c.ComponentRegistry.RegistrationsFor(elementService);
IEnumerable<Object> elements = registrations.Select(cr => c.ResolveComponent(cr, p));
// get distinct elements by type
Array array = elements.GroupBy(o => o.GetType()).Select(o => o.First()).ToArray();
Array array2 = Array.CreateInstance(elementType, array.Length);
array.CopyTo(array2, 0);
Object collection = Activator.CreateInstance(collectionType, new Object[] { array2 });
return collection;
}).As(service)
.CreateRegistration();
return new IComponentRegistration[] { registration };
}
}
你可以像这样使用它:
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<A1>().As<IA>();
builder.RegisterType<A1>().As<IA>();
builder.RegisterType<A2>().As<IA>();
builder.RegisterSource(new CustomEnumerableRegistrationSource());
IContainer container = builder.Build();
IEnumerable<IA> services = container.Resolve<IEnumerable<IA>>();
Console.WriteLine(services.Count());
此注册是原始CollectionRegistrationSource的简化版本。请查看CollectionRegistrationSource.cs的源代码以获得更完整的注册版本。