如何在Asp.net Core rc1中的静态方法中使用DI [英] How to use DI inside a static Method in Asp.net Core rc1
问题描述
我看到defaut模板使用ServiceProvder.GetService<ApplicationDbCotnext>()
初始化DbContext,
但是当您进入静态方法时,我不知道如何获取DbContext
,因为没有ServiceProvider
.
有没有办法获取ServiceProvider
?
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
?
推荐答案
首先,这与asp.net-core本身无关.这与依赖注入的工作方式有关.您必须问自己为什么您的方法是静态的.真的有必要吗?
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?
如果您不能摆脱静态方法,不妨一路引入另一个反模式,即服务定位器模式.简而言之:在Startup类中,您在静态类(例如"ServiceProviderProvider")的静态属性(称为"ServiceProviderSingleton")中放置了对ServiceProvider的引用.这样,您就可以调用"ServiceProviderProvider.ServiceProviderSingleton.GetService()".
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.
这篇关于如何在Asp.net Core rc1中的静态方法中使用DI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!