Where does Unit Of Work belong w/ EF4, IoC (Unity), and Repository?

前端 未结 2 1447
滥情空心
滥情空心 2020-12-11 04:51

I see several questions relating somewhat to this, but I still can\'t find the answer I\'m looking for, so I\'m posting my question. If another question holds the answer (a

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 05:18

    One way is to manage this is to use the method described in http://mfelicio.wordpress.com/2010/02/07/managing-the-entity-framework-objectcontext-instance-lifetime-in-wcf-and-sharing-it-among-repositories/ That article implements the ContextManager for Wcf services. For ASP.NET app we could use something like this.

    public class AspNetDBContextManager : IDBContextManager
        where TContext : IDBContext, new()
    {
        #region IDBContextManager Members
    
        public IDBContext GetDBContext()
        {
            return this.GetOrCreateDbContext();
        }
    
        private IDBContext GetOrCreateDbContext()
        {
            if (HttpContext.Current == null)
            {
                throw new InvalidOperationException("Can be used only within ASP.NET applications");
            }
    
            string dbContextKey = string.Format("__AspNetDBCM__{0}__", HttpContext.Current.GetHashCode());
    
            object dbContext = HttpContext.Current.Items[dbContextKey];
    
            if (dbContext == null)
            {
                dbContext = new TContext();
    
                if (dbContext != null)
                {
                    HttpContext.Current.Items[dbContextKey] = dbContext;
                }
            }
    
            return dbContext as IDBContext;
        }
    
        #endregion
    }
    
    public interface IDBContext
    {
        object Context { get; }
    }
    
    
    public interface IDBContextManager
    {
        IDBContext GetDBContext();
    }
    

提交回复
热议问题