millarnui
millarnui

Reputation: 549

Could not resolve a service of type 'x.y.z'

I'm getting a 500 error when I try access an object I've injected using services.AddSingleton<>() in the ConfigureServices method in Startup.cs:

Could not resolve a service of type proj.Auth.IAuthProvider for the parameter authProvider of method Configure on type proj.Startup.

As far as I can tell from looking at "working" code samples this should be working...

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();
    services.Configure<AppSettings>(Configuration);
    services.AddSingleton<IAuthProvider, TranslatorAuthProvider>();
    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IAuthProvider authProvider)
{
    ...

    app.Run(async context =>
    {
        await authProvider.GetToken();
    });

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

TranslatorAuthProvider.cs:

namespace proj.Auth
{
    public class TranslatorAuthProvider : IAuthProvider
    {
        public TranslatorAuthProvider(IHttpContextAccessor httpContextAccessor, IOptions<AppSettings> settings)
        {
            ...
        }

        public async Task<OAuthToken> GetToken()
        {
            ...
        }
    }
}

IAuthProvider.cs:

namespace proj.Auth
{
    public interface IAuthProvider
    {
        Task<OAuthToken> GetToken();
    }
}

Upvotes: 1

Views: 2519

Answers (1)

Ivan Prodanov
Ivan Prodanov

Reputation: 35502

Yes that's expected. It fails to resolve IHttpContextAccessor, because the IHttpContextAccessor is not registered by default since recently (see #190)

You should register it manually in ConfigureServices() like so

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Upvotes: 2

Related Questions