Search code examples
c#dependency-injectionautofac

Autofac Resolving MatchingLifetimeScope Collection


I want to resolve an IEnumerable of all services from a named scope, but that doesn't work, because services are also resolved from other named scopes.

Example

var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<B>().As<IMyInterface>().InstancePerMatchingLifetimeScope("B");
containerBuilder.RegisterType<A>().As<IMyInterface>().InstancePerMatchingLifetimeScope("A");

IContainer container= containerBuilder.Build();

ILifetimeScope lifetimeScope = container.BeginLifetimeScope("A");
lifetimeScope.Resolve<IEnumerable<IMyInterface>>();

throws DependencyResolutionException: Unable to resolve the type 'ConsoleApp2.B' because the lifetime scope it belongs in can't be located.

Is there a way to only resolve services from the current scope?

I am using Autofac 6.0.0


Solution

  • It appears you've encountered a bug. There's a similar issue already open for this; I'll add a repro of your specific case to the issue and update it to be flagged as a bug rather than an enhancement.

    I'm unaware of any workarounds to solve this issue at the moment. Sorry.