在 Web 应用程序的生命周期中实例化一次服务层和存储库
在我的网络应用程序的生命周期中,我知道我的所有服务和存储库都会被调用。我想在 Web 应用程序启动期间实例化它们一次,并引用我的代码中的实例化引用。
是否存在一种通用模式,可以在 Web 应用程序的生命周期内仅实例化您的服务/存储库一次,而不将它们设为静态或单例。
我想避免将我的服务/存储库设置为静态类或单例以实现可测试性,但是当它们被设计为无状态时,在每个 Web 请求上实例化它们似乎并不正确,而且我知道在应用程序的生命周期中都将需要它们。
我正在使用 c#/asp.net。
During the life of my web application I know all of my services and repositories will be called. I would like to instantiate them once during the startup of the web application and refer to the instantiated references in my code.
Is there a common pattern for instantiating your services/repositories only once during the lifetime of a web application without making them static or singletons.
I would like to avoid making my services/repositories static classes or singletons for testability however instantiating them on every web request doesn't seem right when they are designed to be stateless and I know they will all be needed during the lifetime of the application.
I am using c#/asp.net.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你需要的概念叫做IoC/DI,有很多这样的框架。当您有一个像 CustomerService 这样的类并且您需要其中的 CustomerRepository 时,根据定义,这是一个依赖项,您应该通过 CustomerService 的构造函数传递它 - 但接下来的问题是您将在哪里实例化 CustomerService?好吧,谁使用该服务也应该通过构造函数获取它,它可能是 CustomerPresenter,或其他一些不相关的类。我的观点是,通过进行依赖项注入,您可以将代码构建为一个非常单一的点,其中 IoC / DI 框架根据您的规则解决这些依赖项。
在程序的最顶部,您会看到类似的内容:
并且所有内容都会在幕后自动组合在一起。
为了实现这一点,这里有一个 StructureMap 的示例:
通过这个,您可以保持可测试性。我在这里简化了很多事情,所以这并没有多大用处,但是网上有很多 IoC / DI 资源,所以请查看它们。
注意:对于 Web 应用程序,您需要检查每个请求的处理生命周期,整个 Web 应用程序很少有单例。
The concept you need is called IoC / DI, and there are many frameworks for this. When you have a class like CustomerService and you need a CustomerRepository in it, by definition that is a dependancy, and you should pass it through the constructor of CustomerService - but then there is the question where you will instantiate CustomerService? Well, who uses that service should get it through constuctor too, it is maybe a CustomerPresenter, or some other class, irrelevant. My point is that with doing dependancy injections you structure your code to a very single point where an IoC / DI framework resolves those dependancies accoring to your rules.
At the very top of the program, you would have something like:
and everything will automatically come together behind the scenes.
To achieve this, here is an example with StructureMap:
With this, you keep the testability. I've simplified things a lot here, so this isn't much usable as-is, but there are plenty IoC / DI resources online, so check them out.
Note: for web applications you will want to check out handling lifecycle per request, you will rarely have singletons for entire web application.
依赖注入框架将负责对象的生命周期。
例如,
有很多 DI 框架,选择最适合您的。
Dependency Injection frameworks will take care of the lifetime of your objects.
Eg
There are many DI frameworks choose what suits you best.