无法解析类型为' x.y.z'的服务

时间:2016-06-14 14:08:16

标签: c# asp.net-core

当我尝试访问services.AddSingleton<>()ConfigureServices方法Startup.cs中使用proj.Auth.IAuthProvider注入的对象时,我收到了500错误:

无法为authProvider类型的方法Configure的参数proj.Startup解析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?}"); }); } 类型的服务。

据我所知,&#34;工作&#34;这个代码样本应该正常工作......

Startup.cs:

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

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

TranslatorAuthProvider.cs:

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

IAuthProvider.cs:

{{1}}

1 个答案:

答案 0 :(得分:2)

是的,这是预料之中的。它无法解析IHttpContextAccessor,因为最近默认情况下未注册IHttpContextAccessor(请参阅#190

您应该在ConfigureServices()中手动注册

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();