在DAL层中,建立工厂类
namespace DAL { public static class SysDbContextFactory { /// <summary> /// 从Http上下文中获取EF容器 /// </summary> /// <returns></returns> public static SysDbContext GetSysDbContext() { var context = HttpContext.Current.Items[nameof(SysDbContext)] as SysDbContext; if (context == null) { context = new SysDbContext(); HttpContext.Current.Items[nameof(SysDbContext)] = context; } return context as SysDbContext; } } }
然后在DAL 传入 构造函数
namespace DAL { public class ProductService: EntitryBaseHelper<Product>, IProductService { public ProductService() : base(SysDbContextFactory.GetSysDbContext()) { } public ProductService(SysDbContext _sysDbContext) : base(_sysDbContext) { } } }