autofac/Autofac.WebApi

Injecting a registered named service is not working as expected.

vasugupta1 opened this issue · 1 comments

Background :

  • Autofac 4.2.1(tried with the latest version of Autofac and the issue is still present) ,
  • WebApi project .netcore 2.2

Issue :
I have two instances of the same service, which I register to the ContainerBuilder with Name:

        builder.RegisterType<ServiceOne>().Named<IService>("ServiceOne").SingleInstance();
        builder.RegisterType<ServiceTwo>().Named<IService>("ServiceTwo").SingleInstance();

I then inject the named serivces to my controller classes as required:

        builder.Register(c => new KeysController(c.ResolveNamed<IService>("ServiceOne")));
        builder.Register(c => new ValuesController(c.ResolveNamed<IService>("ServiceTwo")));

Autofac is not able to resolve the IService for both of my controllers by name.

The Exception :
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'AutoFacNaming.IService' while attempting to activate 'AutoFacNaming.Controllers.ValuesController'.

I have attached a sample project which outlines the issue.
autofacNaming.zip

This issue should probably have been raised in the https://github.com/autofac/Autofac.Extensions.DependencyInjection repository, the issue isn't with the older WebApi integration.

Regardless, I believe you might be falling foul of the ASP.NET Core 'Controllers as Services' problem, with the fix described here:
https://autofaccn.readthedocs.io/en/latest/integration/aspnetcore.html#controllers-as-services