我已经阅读了几篇文章,但是似乎没有什么适合我的问题。
我正在使用.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
}
答案 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
的单例实例。