在MVC 4应用程序中使用Unity with Entity Framework的最佳实践是什么

RHA*_*HAD 4 c# entity-framework dependency-injection unity-container asp.net-mvc-4

我正在努力使用MVC 4应用程序中的Entityframework,利用Unity for Dependency注入和Automapper将对象自动化到DTO.我从一个问题跑到另一个问题,EF有时会返回旧数据,所以我认为我的设计不够好.

我有什么:

要在我的Application_Start中配置Unity:

var UnityContainer = UnityConfig.GetConfiguredContainer();
Mapper.Initialize(cfg => cfg.ConstructServicesUsing(type => UnityContainer.Resolve(type)));
UnityContainer.Resolve<AutoMapperConfig>().MapAutoMapper();
...
Run Code Online (Sandbox Code Playgroud)

在UnityConfig.RegisterTypes中:

container.RegisterType<IMyContext, MyContext>(new ContainerControlledLifetimeManager())
...
Run Code Online (Sandbox Code Playgroud)

我的存储库使用构造函数依赖注入:

public class MSSQLTenantRepository : IDalTenantRepository
{
   private readonly IMyContext _Db;
   public MSSQLTenantRepository(IMyContext db)
   {
      Db = db;
   }
...
Run Code Online (Sandbox Code Playgroud)

我的控制器也使用构造函数依赖注入:

public class TenantController : Controller
{
   private readonly ITenantRepository _TenantRepository;
   public TenantController(ITenantRepository tenantRepository,
   {
      _TenantRepository = tenantRepository;
   }
...
Run Code Online (Sandbox Code Playgroud)

自动配置配置:

public class AutoMapperConfig
{
    private readonly ITenantRepository _TenantRepository;
    public AutoMapperConfig(ITenantRepository tenantRepository)
    {
        _TenantRepository = tenantRepository;
    }
...
Run Code Online (Sandbox Code Playgroud)

问题:我有时会从第一个请求中获取旧数据.

当我手动更新de SQL Server中的数据时,EF的返回对象不会反映更改

当我尝试不同的选项时,我也遇到了关于多个上下文的错误(由于Automapper)

我的问题:

  • 使用Unity,MVC4,EF 6,存储库和Automapper的最佳做法是什么?
  • 放置代码的位置(例如,在Unity.AaxActivator的global.asax.c或UnitiConfig.cs中?
  • 我是否需要显式处理dbcontext,如果是这样的话:在哪里这样做?

关于这个主题有很多说法,但没有任何内容涵盖所有内容.

Wik*_*hla 6

 container.RegisterType<IMyContext, MyContext>(
     new ContainerControlledLifetimeManager())
Run Code Online (Sandbox Code Playgroud)

这是相当糟糕的,它使你的上下文成为一个单例.这样,不仅多个请求共享相同的上下文,而且存在并发问题的风险,而且这种共享上下文的内存消耗也会在没有控制的情况下增长.

相反,您希望有一个"按请求"的生命周期,其中为每个单独的请求建立新的上下文:

http://www.wiktorzychla.com/2013/03/unity-and-http-per-request-lifetime.html

public class PerRequestLifetimeManager : LifetimeManager
{
  private readonly object key = new object();

  public override object GetValue()
  {
    if (HttpContext.Current != null && 
        HttpContext.Current.Items.Contains(key))
        return HttpContext.Current.Items[key];
    else
        return null;
  } 

  public override void RemoveValue()
  {
    if (HttpContext.Current != null)
        HttpContext.Current.Items.Remove(key);
  }

  public override void SetValue(object newValue)
  {
    if (HttpContext.Current != null)
        HttpContext.Current.Items[key] = newValue;
  }
}
Run Code Online (Sandbox Code Playgroud)

container.RegisterType<IMyContext, MyContext>(new PerRequestLifetimeManager())
Run Code Online (Sandbox Code Playgroud)

我不确定你的AutoMapperConfig课做了什么以及为什么要将一个存储库注入其中.这可能是另一个终身问题,但我需要澄清一下.