Miguel Moura
Miguel Moura

Reputation: 39364

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?

Upvotes: 0

Views: 297

Answers (1)

Cyril Durand
Cyril Durand

Reputation: 16192

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

Upvotes: 3

Related Questions