我尝试在Startup.cs
文件中使用Configure
方法中的自定义DbContext时收到以下异常。我使用ASP.NET核心版本2.0.0-preview1-005977ASP.NET Core 2中的依赖注入抛出异常
未处理的异常:System.Exception的:无法解析类型的服务“Communicator.Backend.Data.CommunicatorContext”为参数“的DbContext”类型为'Communicator.Backend.Startup'的方法'Configure'。 ---> System.InvalidOperationException:无法解析根提供程序的范围服务'Communicator.Backend.Data.CommunicatorContext'。
当我尝试接收其他实例时,也会抛出此异常。
未处理的异常:System.Exception的:无法解析型 'Communicator.Backend.Services.ILdapService'
...
这里是我的ConfigureServices
和Configure
方法的服务。
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CommunicatorContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddCookieAuthentication();
services.Configure<LdapConfig>(Configuration.GetSection("Ldap"));
services.AddScoped<ILdapService, LdapService>();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, CommunicatorContext dbContext, ILdapService ldapService)
{
app.UseAuthentication();
app.UseWebSockets();
app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await Echo(context, webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
app.UseMvc();
DbInitializer.Initialize(dbContext, ldapService);
}
我做了第一次改变,它的工作原理。谢谢 –
谢谢,这解决了我的问题。如果我可以添加更多,在测试这两个选项之后,我发现我仍然需要修改'ConfigureServices'以返回'void'(默认情况下)以返回'IServiceProvider',以便使第二个选项正常工作。 – muhihsan