Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Injecting a registered named service is not working as expected. #51

Closed
vasugupta1 opened this issue Nov 29, 2019 · 1 comment
Closed

Comments

@vasugupta1
Copy link

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

@alistairjevans
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants