How to use DI inside a static Method in Core rc1

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 ?


Well, first of all, this has nothing to do with 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.

I 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):

Need Your Help

installing appcelerator app on android 4.0.4 device

android appcelerator-titanium

i am getting issue with installing appcelerator app on android 4.0.4 device

Mocking wcf in silverlight

wcf silverlight unit-testing mocking moq

I thought that I could create a WCF in and call it in Silverlight. I would inject an interface to the WCF. Then in my unit test I would mock the wcf....