How to use DI inside a static Method in Asp.net 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 ?

Answers


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.


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

https://github.com/aspnet/Mvc/blob/760c8f38678118734399c58c2dac981ea6e47046/src/Microsoft.AspNetCore.Mvc.Core/Builder/MvcApplicationBuilderExtensions.cs


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....