使用Autofac解析某些类型的所有类型

时间:2016-07-29 15:12:12

标签: c# asp.net-core autofac

在ASP.NET核心项目Startup上我有:

services.AddScoped<SingleInstanceFactory>(x => y => x.GetRequiredService(y));
services.AddScoped<MultiInstanceFactory>(x => y => x.GetRequiredServices(y));

我正在尝试使用Autofac 4,所以我尝试了:

builder.Register<SingleInstanceFactory>(y => z => y.Resolve(z)).InstancePerLifetimeScope();
builder.Register<MultiInstanceFactory>(y => z => y.ResolveAll(z)).InstancePerLifetimeScope();

然而,似乎Autofac没有ResolveAll方法。

我该如何解决这个问题?

更新

我还尝试创建以下扩展程序:

public static T[] ResolveAll<T>(this IContainer container) {
  return container.Resolve<IEnumerable<T>>().ToArray();
}

public static Object[] ResolveAll(this IContainer container, Type type) {
  Type enumerable = typeof(IEnumerable<>).MakeGenericType(type);
  return (Object[])container.ResolveService(new TypedService(enumerable));
}

使用如下:

x.Register<MultiInstanceFactory>(y => z => y.ResolveAll(z)).InstancePerLifetimeScope();   

但我收到错误:

Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type

不确定我错过了什么......有什么想法吗?

1 个答案:

答案 0 :(得分:3)

要解决T的所有注册服务,您可以解析IEnumerable<T>

顺便说一下,您正在尝试注册 Autofac 不需要的委托(请参阅delegate factory),因为 Autofac 会自动使用合成(请参阅Composing Relationship Types)您无需注册任何内容。

如果您要解析MultiInstanceFactorySingleInstanceFactory,则无需在 Autofac 中注册任何内容