简体   繁体   中英

ResolveAll of certain type with Autofac

On an ASP.NET Core project Startup I have:

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

I am trying to use Autofac 4 instead so I tried:

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

However, it seems Autofac does not have a ResolveAll method.

How can I solve this?

Update

I also tried to create the following extensions:

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

And use it as follows:

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

But I get the error:

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

Not sure what I am missing ... Any idea?

To resolve all registered service of T, you can resolve IEnumerable<T>

By the way, you are trying to register a delegate which is not required by Autofac (see delegate factory ) and because Autofac automatically use composition (see Composing Relationship Types ) you are not required to register anything.

If you want to resolve a MultiInstanceFactory or SingleInstanceFactory you don't need to register anything in Autofac

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM