当我尝试访问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}}
答案 0 :(得分:2)
是的,这是预料之中的。它无法解析IHttpContextAccessor
,因为最近默认情况下未注册IHttpContextAccessor
(请参阅#190)
您应该在ConfigureServices()
中手动注册
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();