Reputation: 736
I see defaut template use ServiceProvder.GetService<ApplicationDbCotnext>()
to initialize a DbContext,
But when you inside a Static Method, I have no idea how to get a DbContext
, because there is no ServiceProvider
.
Is there a way to get the ServiceProvider
?
Upvotes: 5
Views: 13757
Reputation: 1145
If we have a look at Microsoft's static methods (extension) - they seem not to use logging there - just throw appropriate Exception, for example in UseMvc method (for StartUp class):
Upvotes: 0
Reputation: 5366
Well, first of all, this has nothing to do with asp.net-core per se. This has more to do with how Dependency Injection works. You have to ask yourself why your method is static. Is that really necessary?
If you can't get rid of your static method, you might as well go all the way and introduce another anti-pattern, the Service Locator Pattern. In short: In the Startup class you put a reference to the ServiceProvider in a static property (call it for instance "ServiceProviderSingleton") of a static class (for instance "ServiceProviderProvider"). This way you can just call "ServiceProviderProvider.ServiceProviderSingleton.GetService()".
Again, i suggest giving your overal design a critical look. But if this is what you need/want then I hope it helped.
Upvotes: 7