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 :-)

1 Answers 11

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.

upvote
  flag
Thanks, now works fine! I got confused by that other hings weren't interfaces (maybe they should be?) – Bubiec

Not the answer you're looking for? Browse other questions tagged or ask your own question.