简体   繁体   中英

Dependency injection does not work when added with interface

when I add a service to the configure services method in my startup class

services.AddSingleton<IGoogleApi, GoogleApi>();

I get the following error.

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[0] An unhandled exception has occurred while executing the request System.InvalidOperationException: Unable to resolve service for type 'MultilanguageTranslatorAPI.Services.GoogleApi' while attempting to activate 'MultilanguageTranslatorAPI.Controllers.WordsController'.

If I change that into (removed interface)

services.AddSingleton<GoogleApi, GoogleApi>();

the error is gone, everything works fine. But why? What is wrong with my class? Constructor might be suspicious.

public WordsController(TranslatorDbContext context, UserManager<User> userManager, GoogleApi api)
    {
        _userManager = userManager;
        _context = context;
        _api = api;
    }

public class GoogleApi : IGoogleApi
{
    private readonly TranslationClient _client;
    private readonly string jsonPath = "Json\\MultilanguageTranslator-82ea38c537d3.json";

    public GoogleApi()
    {
        using (var jsonStream = new FileStream(jsonPath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            _client = TranslationClient
                .Create(GoogleCredential.FromStream(jsonStream));
        }
    }

How should look the correct code for this implementation? Thanks in advance :-)

Your controller is taking the concrete type, GoogleApi in it's constructor, here.

public WordsController(TranslatorDbContext context, UserManager<User> userManager, GoogleApi api)

It should instead take the type IGoogleApi , like so:

public WordsController(TranslatorDbContext context, UserManager<User> userManager, IGoogleApi api)

When you use the concrete type, the IOC container isn't able to use it's singleton mapping of IGoogleApi to GoogleApi , as that's not the type of dependency requested.

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