本文介绍了ASP.NET Core 2 中的依赖注入引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I receive following exception when I try to use custom DbContext in Configure method in Startup.cs file. I use ASP.NET Core in version 2.0.0-preview1-005977

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

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

This exception is also thrown in case when I try to receive other instance.

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

这是我的 ConfigureServicesConfigure 方法.

Here are my ConfigureServices and Configure methods.

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);
}

推荐答案

引用文档

服务可在启动

ASP.NET Core 依赖注入提供应用程序服务应用程序的启动.您可以通过包括以下内容来请求这些服务适当的接口作为 Startup 类的参数构造函数或其 ConfigureConfigureServices 方法之一.

ASP.NET Core dependency injection provides application services during an application's startup. You can request these services by including the appropriate interface as a parameter on your Startup class's constructor or one of its Configure or ConfigureServices methods.

按顺序查看Startup类中的每个方法他们被称为,可能会要求以下服务参数:

Looking at each method in the Startup class in the order in which they are called, the following services may be requested as parameters:

  • 在构造函数中:IHostingEnvironment, ILoggerFactory
  • ConfigureServices方法中:IServiceCollection
  • Configure方法中:IApplicationBuilderIHostingEnvironmentILoggerFactory, IApplicationLifetime
  • In the constructor: IHostingEnvironment, ILoggerFactory
  • In the ConfigureServices method: IServiceCollection
  • In the Configure method: IApplicationBuilder, IHostingEnvironment, ILoggerFactory, IApplicationLifetime

您正在尝试解决启动期间不可用的服务,

You are trying to resolve services that are not available during startup,

...CommunicatorContext dbContext, ILdapService ldapService) {

这会给你你得到的错误.如果您需要访问实现,则需要执行以下操作之一:

which will give you the errors you are getting. If you need access to the implementations then you need to do one of the following:

  1. 修改 ConfigureServices 方法并从服务集合访问它们.即

  1. Modify the ConfigureServices method and access them there from the service collection. i.e.

public IServiceProvider 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();

    // Build the intermediate service provider
    var serviceProvider = services.BuildServiceProvider();

    //resolve implementations
    var dbContext = serviceProvider.GetService<CommunicatorContext>();
    var ldapService = serviceProvider.GetService<ILdapService>();
    DbInitializer.Initialize(dbContext, ldapService);

    //return the provider
    return serviceProvider();
}

  • 修改 ConfigureServices 方法以返回 IServiceProvider,Configure 方法获取一个 IServiceProvider,然后在那里解析您的依赖项.即

  • Modify the ConfigureServices method to return IServiceProvider, Configure method to take a IServiceProvider and then resolve your dependencies there. i.e.

    public IServiceProvider 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();
    
        // Build the intermediate service provider then return it
        return services.BuildServiceProvider();
    }
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                          ILoggerFactory loggerFactory, IServiceProvider serviceProvider) {
    
        //...Other code removed for brevity
    
        app.UseMvc();
    
        //resolve dependencies
        var dbContext = serviceProvider.GetService<CommunicatorContext>();
        var ldapService = serviceProvider.GetService<ILdapService>();
        DbInitializer.Initialize(dbContext, ldapService);
    }
    

  • 这篇关于ASP.NET Core 2 中的依赖注入引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-24 00:35