【发布时间】:2015-08-13 08:31:09
【问题描述】:
我在构造函数中使用 DI。 BaseShoppingCart 是一项服务,我在其中设置了 ShoppingCartId(用于购物车项目)。 这是构造函数:
public BaseShoppingCart( HttpContextBase context, IRepository<TCart> cart ,IProductService productservice)
{
_context = context;
_cart = cart;
_productService = productservice;
ShoppingCartId = _context.Request.IsAuthenticated ? _context.User.Identity.Name : getSessionCartId();
}
- 如果我在 DI 容器 (Unity) 中设置 Transientlifetimemanager(默认),则不会显示任何错误。
- 如果我设置 PerThreadLifetimeManager,任何用户都可能获得另一个用户的购物车!正如我从这篇文章中读到的Why is PerThreadLifetimeManager used in this example? - 线程比请求长,所以在这种情况下第二次调用 ShoppingCartController 可能不会调用 BaseShoppingCart 的 ctor。而是从容器返回现有的 BaseShoppingCart 对象(另一个用户的对象)。
我需要你的意见:
- 我是否正确理解了这个问题?
- 在哪些情况下 PerThreadLifetimemanager 替代 Transientlifetimemanager 有用?
谢谢!
【问题讨论】:
-
购物车是特定于用户的,因此在这种情况下使用每个线程的生命周期是没有意义的。但是可能有其他服务不是用户特定的;例如,如果所有用户都可以访问相同的产品,则 IProductService 可以是每个线程的。
-
谢谢! DBContext 应该是 Per-thread 吗?
-
可能不会;通常 DBContext 是每个请求的
标签: c# asp.net-mvc-4 dependency-injection unity-container