Net Core 2 Console App - DI 'Unable to resolve service for type…'











up vote
0
down vote

favorite












I've been reading several posts but nothing seems to fit to my problem.



I'm developing a console app with .Net Core 2.1 and EF Core trying to follow Microsoft's advices but I'm facing with the next problem.



I've a project named myproject.data which contains all the interfaces and services. This one, for example



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


Then, I have all the methods of my app separated and all of them inherit from the same class. In this Base.cs class I setup the 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();
}


When I try to use the LeagueService in one of the methods I get the 'Unable to resolve service for type myproject.stats.statsContext' error



GetNextMatches.cs



private ILeaguesService _leagueService;

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

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









share|improve this question
























  • Why not use a traditional Startup.cs?
    – Marcus Höglund
    Nov 22 at 13:49






  • 1




    Maybe I'm wrong but AFAIK a console app doesn't have Startup.cs
    – Rafael Osuna Dominguez
    Nov 22 at 14:01








  • 1




    @RafaelOsunaDominguez Startup.cs is just a file to place the various Configure methods. Your code splits that configuration between Base.cs and GetNextMatches.cs so it's hard to understand which part does what. GetNextMatches shouldn't try to access the DI and configuration itself, its constructor should receive whatever is needed as a parameter. The class itself should be created using DI
    – Panagiotis Kanavos
    Nov 22 at 14:32






  • 1




    @RafaelOsunaDominguez where did GetNextMatches find _serviceProvider and _config anyway? Those are defined in Base.cs. Does it inherit from Base? In this case it breaks the DI/Configuration model completely. You end up with a different DI and Configuration container per object
    – Panagiotis Kanavos
    Nov 22 at 14:33










  • Won't you need to register a concrete for statsContext so that the DI container can push it into the ctor for LeagueService? At least, I think that's what the error is saying.
    – David Jetter
    Nov 22 at 15:29















up vote
0
down vote

favorite












I've been reading several posts but nothing seems to fit to my problem.



I'm developing a console app with .Net Core 2.1 and EF Core trying to follow Microsoft's advices but I'm facing with the next problem.



I've a project named myproject.data which contains all the interfaces and services. This one, for example



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


Then, I have all the methods of my app separated and all of them inherit from the same class. In this Base.cs class I setup the 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();
}


When I try to use the LeagueService in one of the methods I get the 'Unable to resolve service for type myproject.stats.statsContext' error



GetNextMatches.cs



private ILeaguesService _leagueService;

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

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









share|improve this question
























  • Why not use a traditional Startup.cs?
    – Marcus Höglund
    Nov 22 at 13:49






  • 1




    Maybe I'm wrong but AFAIK a console app doesn't have Startup.cs
    – Rafael Osuna Dominguez
    Nov 22 at 14:01








  • 1




    @RafaelOsunaDominguez Startup.cs is just a file to place the various Configure methods. Your code splits that configuration between Base.cs and GetNextMatches.cs so it's hard to understand which part does what. GetNextMatches shouldn't try to access the DI and configuration itself, its constructor should receive whatever is needed as a parameter. The class itself should be created using DI
    – Panagiotis Kanavos
    Nov 22 at 14:32






  • 1




    @RafaelOsunaDominguez where did GetNextMatches find _serviceProvider and _config anyway? Those are defined in Base.cs. Does it inherit from Base? In this case it breaks the DI/Configuration model completely. You end up with a different DI and Configuration container per object
    – Panagiotis Kanavos
    Nov 22 at 14:33










  • Won't you need to register a concrete for statsContext so that the DI container can push it into the ctor for LeagueService? At least, I think that's what the error is saying.
    – David Jetter
    Nov 22 at 15:29













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I've been reading several posts but nothing seems to fit to my problem.



I'm developing a console app with .Net Core 2.1 and EF Core trying to follow Microsoft's advices but I'm facing with the next problem.



I've a project named myproject.data which contains all the interfaces and services. This one, for example



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


Then, I have all the methods of my app separated and all of them inherit from the same class. In this Base.cs class I setup the 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();
}


When I try to use the LeagueService in one of the methods I get the 'Unable to resolve service for type myproject.stats.statsContext' error



GetNextMatches.cs



private ILeaguesService _leagueService;

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

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









share|improve this question















I've been reading several posts but nothing seems to fit to my problem.



I'm developing a console app with .Net Core 2.1 and EF Core trying to follow Microsoft's advices but I'm facing with the next problem.



I've a project named myproject.data which contains all the interfaces and services. This one, for example



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


Then, I have all the methods of my app separated and all of them inherit from the same class. In this Base.cs class I setup the 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();
}


When I try to use the LeagueService in one of the methods I get the 'Unable to resolve service for type myproject.stats.statsContext' error



GetNextMatches.cs



private ILeaguesService _leagueService;

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

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






c# dependency-injection .net-core console-application






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 14:25









Kirk Larkin

18.8k33654




18.8k33654










asked Nov 22 at 13:45









Rafael Osuna Dominguez

1341416




1341416












  • Why not use a traditional Startup.cs?
    – Marcus Höglund
    Nov 22 at 13:49






  • 1




    Maybe I'm wrong but AFAIK a console app doesn't have Startup.cs
    – Rafael Osuna Dominguez
    Nov 22 at 14:01








  • 1




    @RafaelOsunaDominguez Startup.cs is just a file to place the various Configure methods. Your code splits that configuration between Base.cs and GetNextMatches.cs so it's hard to understand which part does what. GetNextMatches shouldn't try to access the DI and configuration itself, its constructor should receive whatever is needed as a parameter. The class itself should be created using DI
    – Panagiotis Kanavos
    Nov 22 at 14:32






  • 1




    @RafaelOsunaDominguez where did GetNextMatches find _serviceProvider and _config anyway? Those are defined in Base.cs. Does it inherit from Base? In this case it breaks the DI/Configuration model completely. You end up with a different DI and Configuration container per object
    – Panagiotis Kanavos
    Nov 22 at 14:33










  • Won't you need to register a concrete for statsContext so that the DI container can push it into the ctor for LeagueService? At least, I think that's what the error is saying.
    – David Jetter
    Nov 22 at 15:29


















  • Why not use a traditional Startup.cs?
    – Marcus Höglund
    Nov 22 at 13:49






  • 1




    Maybe I'm wrong but AFAIK a console app doesn't have Startup.cs
    – Rafael Osuna Dominguez
    Nov 22 at 14:01








  • 1




    @RafaelOsunaDominguez Startup.cs is just a file to place the various Configure methods. Your code splits that configuration between Base.cs and GetNextMatches.cs so it's hard to understand which part does what. GetNextMatches shouldn't try to access the DI and configuration itself, its constructor should receive whatever is needed as a parameter. The class itself should be created using DI
    – Panagiotis Kanavos
    Nov 22 at 14:32






  • 1




    @RafaelOsunaDominguez where did GetNextMatches find _serviceProvider and _config anyway? Those are defined in Base.cs. Does it inherit from Base? In this case it breaks the DI/Configuration model completely. You end up with a different DI and Configuration container per object
    – Panagiotis Kanavos
    Nov 22 at 14:33










  • Won't you need to register a concrete for statsContext so that the DI container can push it into the ctor for LeagueService? At least, I think that's what the error is saying.
    – David Jetter
    Nov 22 at 15:29
















Why not use a traditional Startup.cs?
– Marcus Höglund
Nov 22 at 13:49




Why not use a traditional Startup.cs?
– Marcus Höglund
Nov 22 at 13:49




1




1




Maybe I'm wrong but AFAIK a console app doesn't have Startup.cs
– Rafael Osuna Dominguez
Nov 22 at 14:01






Maybe I'm wrong but AFAIK a console app doesn't have Startup.cs
– Rafael Osuna Dominguez
Nov 22 at 14:01






1




1




@RafaelOsunaDominguez Startup.cs is just a file to place the various Configure methods. Your code splits that configuration between Base.cs and GetNextMatches.cs so it's hard to understand which part does what. GetNextMatches shouldn't try to access the DI and configuration itself, its constructor should receive whatever is needed as a parameter. The class itself should be created using DI
– Panagiotis Kanavos
Nov 22 at 14:32




@RafaelOsunaDominguez Startup.cs is just a file to place the various Configure methods. Your code splits that configuration between Base.cs and GetNextMatches.cs so it's hard to understand which part does what. GetNextMatches shouldn't try to access the DI and configuration itself, its constructor should receive whatever is needed as a parameter. The class itself should be created using DI
– Panagiotis Kanavos
Nov 22 at 14:32




1




1




@RafaelOsunaDominguez where did GetNextMatches find _serviceProvider and _config anyway? Those are defined in Base.cs. Does it inherit from Base? In this case it breaks the DI/Configuration model completely. You end up with a different DI and Configuration container per object
– Panagiotis Kanavos
Nov 22 at 14:33




@RafaelOsunaDominguez where did GetNextMatches find _serviceProvider and _config anyway? Those are defined in Base.cs. Does it inherit from Base? In this case it breaks the DI/Configuration model completely. You end up with a different DI and Configuration container per object
– Panagiotis Kanavos
Nov 22 at 14:33












Won't you need to register a concrete for statsContext so that the DI container can push it into the ctor for LeagueService? At least, I think that's what the error is saying.
– David Jetter
Nov 22 at 15:29




Won't you need to register a concrete for statsContext so that the DI container can push it into the ctor for LeagueService? At least, I think that's what the error is saying.
– David Jetter
Nov 22 at 15:29












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










When using the ServiceProvider DI you have to register all of the classes in the hierarchy. The DI container is trying to create your LeagueService class but to call its constructor it needs to create an instance of statsContext. However it cannot find that in its registry so it throws the exception.



The solution is to add statsContext to your services collection.



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


I am going to assume your _context variable is the statsContext you want to inject so you can use your GetContext() method to create the context for you:



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


This will call your GetContext() once to create your single instance of statsContext. Now, whenever you call



_leagueService = _serviceProvider.GetService<ILeaguesService>();


DI will inject the singleton instance of statsContext when it creates your LeageService class.






share|improve this answer





















  • Works perfect but, as a result of @PanagiotisKanavos' comments, I have doubts about whether this is a correct design of the application. So, I've a Base.cs class that I use to share and setup DI and other elements in the classes that really do the tasks
    – Rafael Osuna Dominguez
    Nov 23 at 8:09













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53432374%2fnet-core-2-console-app-di-unable-to-resolve-service-for-type%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote



accepted










When using the ServiceProvider DI you have to register all of the classes in the hierarchy. The DI container is trying to create your LeagueService class but to call its constructor it needs to create an instance of statsContext. However it cannot find that in its registry so it throws the exception.



The solution is to add statsContext to your services collection.



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


I am going to assume your _context variable is the statsContext you want to inject so you can use your GetContext() method to create the context for you:



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


This will call your GetContext() once to create your single instance of statsContext. Now, whenever you call



_leagueService = _serviceProvider.GetService<ILeaguesService>();


DI will inject the singleton instance of statsContext when it creates your LeageService class.






share|improve this answer





















  • Works perfect but, as a result of @PanagiotisKanavos' comments, I have doubts about whether this is a correct design of the application. So, I've a Base.cs class that I use to share and setup DI and other elements in the classes that really do the tasks
    – Rafael Osuna Dominguez
    Nov 23 at 8:09

















up vote
1
down vote



accepted










When using the ServiceProvider DI you have to register all of the classes in the hierarchy. The DI container is trying to create your LeagueService class but to call its constructor it needs to create an instance of statsContext. However it cannot find that in its registry so it throws the exception.



The solution is to add statsContext to your services collection.



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


I am going to assume your _context variable is the statsContext you want to inject so you can use your GetContext() method to create the context for you:



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


This will call your GetContext() once to create your single instance of statsContext. Now, whenever you call



_leagueService = _serviceProvider.GetService<ILeaguesService>();


DI will inject the singleton instance of statsContext when it creates your LeageService class.






share|improve this answer





















  • Works perfect but, as a result of @PanagiotisKanavos' comments, I have doubts about whether this is a correct design of the application. So, I've a Base.cs class that I use to share and setup DI and other elements in the classes that really do the tasks
    – Rafael Osuna Dominguez
    Nov 23 at 8:09















up vote
1
down vote



accepted







up vote
1
down vote



accepted






When using the ServiceProvider DI you have to register all of the classes in the hierarchy. The DI container is trying to create your LeagueService class but to call its constructor it needs to create an instance of statsContext. However it cannot find that in its registry so it throws the exception.



The solution is to add statsContext to your services collection.



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


I am going to assume your _context variable is the statsContext you want to inject so you can use your GetContext() method to create the context for you:



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


This will call your GetContext() once to create your single instance of statsContext. Now, whenever you call



_leagueService = _serviceProvider.GetService<ILeaguesService>();


DI will inject the singleton instance of statsContext when it creates your LeageService class.






share|improve this answer












When using the ServiceProvider DI you have to register all of the classes in the hierarchy. The DI container is trying to create your LeagueService class but to call its constructor it needs to create an instance of statsContext. However it cannot find that in its registry so it throws the exception.



The solution is to add statsContext to your services collection.



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


I am going to assume your _context variable is the statsContext you want to inject so you can use your GetContext() method to create the context for you:



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


This will call your GetContext() once to create your single instance of statsContext. Now, whenever you call



_leagueService = _serviceProvider.GetService<ILeaguesService>();


DI will inject the singleton instance of statsContext when it creates your LeageService class.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 22 at 21:10









Simply Ged

2,0782921




2,0782921












  • Works perfect but, as a result of @PanagiotisKanavos' comments, I have doubts about whether this is a correct design of the application. So, I've a Base.cs class that I use to share and setup DI and other elements in the classes that really do the tasks
    – Rafael Osuna Dominguez
    Nov 23 at 8:09




















  • Works perfect but, as a result of @PanagiotisKanavos' comments, I have doubts about whether this is a correct design of the application. So, I've a Base.cs class that I use to share and setup DI and other elements in the classes that really do the tasks
    – Rafael Osuna Dominguez
    Nov 23 at 8:09


















Works perfect but, as a result of @PanagiotisKanavos' comments, I have doubts about whether this is a correct design of the application. So, I've a Base.cs class that I use to share and setup DI and other elements in the classes that really do the tasks
– Rafael Osuna Dominguez
Nov 23 at 8:09






Works perfect but, as a result of @PanagiotisKanavos' comments, I have doubts about whether this is a correct design of the application. So, I've a Base.cs class that I use to share and setup DI and other elements in the classes that really do the tasks
– Rafael Osuna Dominguez
Nov 23 at 8:09




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53432374%2fnet-core-2-console-app-di-unable-to-resolve-service-for-type%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

Calculate evaluation metrics using cross_val_predict sklearn

Insert data from modal to MySQL (multiple modal on website)