Net Core 2控制台应用程序-DI'无法解析类型的服务...'

时间:2018-11-22 13:45:23

标签: c# dependency-injection .net-core console-application

我已经阅读了几篇文章,但是似乎没有什么适合我的问题。

我正在使用.Net Core 2.1和EF Core开发控制台应用程序,试图遵循Microsoft的建议,但是我面临着下一个问题。

我有一个名为 myproject.data 的项目,其中包含所有接口和服务。例如这个

ILeagueService.cs

public interface ILeaguesService
{
    List<Leagues> GetAllLeaguesValids();
}

LeagueService.cs

private statsContext _context;

public LeaguesService(statsContext context)
{
    _context = context;
}

public List<Leagues> GetAllLeaguesValids()
{
    return _context.Leagues.Where(x => (x.DateFirstMatch != null || x.CurrentLastSeason == true) && x.Active == true).OrderBy(x => x.Id).ToList();
}

然后,我将应用程序的所有方法分开,并且所有方法都继承自同一类。在这个Base.cs类中,我设置了 ServiceProvider

Base.cs

public ServiceProvider _serviceProvider;

public Base()
{
    ConfigureServices();

    _config = new HelperConfig(CONFIG_FILE);
    _html = GetHelperHtml();
    _context = GetContext();
}

private void ConfigureServices()
{
    _serviceProvider = new ServiceCollection()
        .AddScoped<ILeaguesService, LeaguesService>()
        .BuildServiceProvider();
}

当我尝试在其中一种方法中使用LeagueService时,出现“无法解析myproject.stats.statsContext类型的服务”错误

GetNextMatches.cs

private ILeaguesService _leagueService;

public GetNextMatches()
{
   _config.GetSection(AppsettingsModel.BetExplorerUrlsSection).Bind(betExplorerSectionKeys);

    _leagueService = _serviceProvider.GetService<ILeaguesService>(); <-- In this line I get the error
}

1 个答案:

答案 0 :(得分:2)

使用ServiceProvider DI时,必须注册层次结构中的所有类。 DI容器正在尝试创建您的LeagueService类,但是要调用其构造函数,则需要创建statsContext的实例。但是,它无法在其注册表中找到它,因此会引发异常。

解决方案是将statsContext添加到您的服务集合中。

private void ConfigureServices()
{
    _serviceProvider = new ServiceCollection()
        .AddScoped<ILeaguesService, LeaguesService>()
        .AddScoped<statsContext>()
        .BuildServiceProvider();
}

我将假设您的_context变量是您要注入的statsContext,因此您可以使用GetContext()方法为您创建上下文:

private void ConfigureServices()
{
    _serviceProvider = new ServiceCollection()
        .AddScoped<ILeaguesService, LeaguesService>()
        .AddSingleton<statsContext>(GetContext())
        .BuildServiceProvider();
}

这将调用您的GetContext()一次,以创建您的statsContext的单个实例。现在,只要您致电

_leagueService = _serviceProvider.GetService<ILeaguesService>();

DI在创建您的statsContext类时将注入LeageService的单例实例。