John
John

Reputation: 736

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 ?

Upvotes: 5

Views: 13757

Answers (2)

Pavel Biryukov
Pavel Biryukov

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

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

Upvotes: 0

Danny van der Kraan
Danny van der Kraan

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

Related Questions