ResolveAll 某种类型的 Autofac
ResolveAll of certain type with Autofac
在 ASP.NET 核心项目启动时,我有:
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
不确定我错过了什么......有什么想法吗?
解析T的所有注册服务,可以解析IEnumerable<T>
顺便说一下,您正在尝试注册 Autofac 不需要的委托(请参阅 delegate factory) and because Autofac automatically use composition (see Composing Relationship Types),您不需要注册任何内容。
如果您想解决 MultiInstanceFactory
或 SingleInstanceFactory
您不需要在 Autofac
中注册任何内容
在 ASP.NET 核心项目启动时,我有:
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
不确定我错过了什么......有什么想法吗?
解析T的所有注册服务,可以解析IEnumerable<T>
顺便说一下,您正在尝试注册 Autofac 不需要的委托(请参阅 delegate factory) and because Autofac automatically use composition (see Composing Relationship Types),您不需要注册任何内容。
如果您想解决 MultiInstanceFactory
或 SingleInstanceFactory
您不需要在 Autofac