小编M. *_*ski的帖子

ASP.NET Core 2中的依赖注入会引发异常

当我尝试ConfigureStartup.cs文件中的方法中使用自定义DbContext时,我收到以下异常.我在版本2.0.0-preview1-005977中使用ASP.NET Core

未处理的异常:System.Exception:无法为类型为"Communicator.Backend.Startup"的方法"Configure"的参数"dbContext"解析类型为"Communicator.Backend.Data.CommunicatorContext"的服务.---> System.InvalidOperationException:无法从根提供程序解析作用域服务"Communicator.Backend.Data.CommunicatorContext".

当我尝试接收其他实例时,也会抛出此异常.

未处理的异常:System.Exception:无法解析类型为"Communicator.Backend.Services.ILdapService"的服务 ...

这是我ConfigureServicesConfigure方法.

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();
        }
    }); …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection .net-core asp.net-core asp.net-core-2.0

39
推荐指数
5
解决办法
3万
查看次数