How to use DI inside a static Method in Asp.net Core rc1
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.
John
Updated on June 29, 2022Comments
-
John almost 2 years
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 aDbContext
, because there is noServiceProvider
. Is there a way to get theServiceProvider
?