编程语言
首页 > 编程语言> > c#-Unity,使用语句和PerRequestLifetimeManager

c#-Unity,使用语句和PerRequestLifetimeManager

作者:互联网

我在项目中使用Unity.但是我不确定是否应该使用using语句,因为我正在使用PerRequestLifetimeManager.

简单的例子:

注射:

container.RegisterType<IDataContext, MyContext>(new PerRequestLifetimeManager());

用法:

class MyClass
{
     private readonly IDataContext _context;

     public MyClass(IDataContext context)
     {
           _context = context;
     }

     public string MyMethod()
     {
          // 1. Is this needed?
          using (var u = _context)
          {
               var customers = u.Set<Customer>().OrderBy(o => o.Name);
               // ........
          }

          // 2. OR can I just do this
          var customers = _context.Set<Customer>().OrderBy(o => o.Name);

当我在注入中使用PerRequestLifetimeManager()时,这是否否定了using语句的要求,因为无论如何在每次http请求之后都会处理上下文?

解决方法:

使用MVC4时,使用工作单元和存储库模式的最佳实践.在每次创建上下文时,最好将上下文注册到App_Start文件夹中的UnityConfig.cs文件中.如

container.RegisterType<IDataContext, MyContext>(new PerRequestLifetimeManager());

之后,当您启动应用程序时,上下文将处于打开状态,直到您的应用程序关闭为止.因此,不要在使用上下文时使用using语句.它将在使用完毕后处置您的上下文,并且该上下文将不再可用,并且在关闭使用后再使用上下文时,您必须得到一个异常,例如上下文不可用.因此,只需使用

var customers = _context.Set<Customer>().OrderBy(o => o.Name);

标签:asp-net-mvc-4,unity-container,c,entity-framework
来源: https://codeday.me/bug/20191121/2053489.html