使用Castle Windsor的存储库类的适当生命周期 [英] Appropriate lifecycle for repository classes using Castle Windsor

查看:129
本文介绍了使用Castle Windsor的存储库类的适当生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我开始使用温莎时,我认为DI会很简单.现在,这使我越来越困惑.

When I started with Windsor I thought DI would be simple. Now it's causing me more and more confusion.

存储库使我成为具有单例生命周期的类.我应该有一个FooRepository实例,以在应用程序的生命周期内将Foos加载并保存到数据库中.

A repository strikes me as a class with a singleton lifecycle. I should have a single instance of a FooRepository to load and save Foos to the database during the application's lifetime.

但是,每个存储库都包含对UnitOfWork的引用,该引用进行脏检查,与数据库一起使用等.UnitOfWork具有PerWebRequest的生命周期-将UnitOfWork设为单例完全没有意义,因为单例实例可以(例如)同时刷新多个用户会话所做的更改.

However, each repository holds a reference to a UnitOfWork, which does the dirty checking, works with the database etc. The UnitOfWork has a lifecycle of PerWebRequest - it makes no sense at all for the UnitOfWork to be a singleton, as a singleton instance could (for example) flush the changes made by several user sessions at the same time.

因此,然后我有一个单例FooRepository,其中包含对UnitOfWork的引用,该引用在会话结束时被释放!我什至不知道会对存储库的行为产生什么影响,但这听起来并不好.

So then I have a singleton FooRepository holding a reference to a UnitOfWork, which at the end of the session gets disposed! I'm not even sure what effect that would have on the repository's behaviour, but it doesn't sound good.

任何人都可以用简单的英语(好的,也许用一些代码)解释在Web应用程序中管理Repository和UnitOfWork类的生命周期的适当方法吗?

Can anyone explain, in simple English (okay, maybe with some code), the appropriate way to manage the lifecycle of Repository and UnitOfWork classes in a web app?

推荐答案

经验法则是-组件不应该依赖于其他组件而不会生存.

Rule of thumb is - component should not depend on other components that will outlive it.

换句话说,瞬态可以依赖单例或按Web请求的组件,但不能相反.

In other words, it's ok for transient to depend on singleton, or per-web-request component, but not the other way around.

我访问存储库的方式-UoW场景是我的UoW是基于Web请求的,但是存储库是无状态的且是瞬态的.

The way I approach Repository - UoW scenario is my UoW is per web request, but repositories are stateless and transient.

这篇关于使用Castle Windsor的存储库类的适当生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆