将EF与BLL分开

时间:2016-09-28 05:05:20

标签: c# entity-framework dbcontext

我编写了以下数据库事务包装器:

 public class ExampleWrapper : IDisposable
    {
        public DbContextTransaction Transaction { get; set; }
        public DcatContext DatabaseContext { get; set; }

        public ExampleWrapper ()
        {
            DatabaseContext = new someContext();
            Transaction = DatabaseContext.Database.BeginTransaction();
        }


        public void Dispose()
        {
          Transaction.Dispose();                      
        }


        public void Commit()
        {
           Transaction.Commit();

        }

        public void RollBack()
        {
            Transaction.Rollback();
        }
    }

我的代码与DAL中的代码类似:

public async Task<Object> Retrieve(string Id)
        {

            using (var context= new  SomeContext())
            {
                return Context.Object.Find(id);
            }
        }

我试图将业务层与任何Entity Framework依赖项分开,这就是包装器类的原因。如果我试图从BLL进行交易,例如:

using(var wrapper = new ExampleWrapper())
{
     //make calls to the DAL 
       something.Retrieve(Id)
}

我的问题是我正在初始化Dbcontext两次(这里创建一个事务,同时在DAL中)。有没有任何建议你怎么能做得更好?

PS:仅以事务中的检索为例。

1 个答案:

答案 0 :(得分:0)

您可以使用依赖注入(例如Ninject)将DbContext注入到 包装。然后,您可以定义DBContext实例的生存期。如果它是Web应用程序,那么您可以将DbContext的生命周期定义为Web请求(InRequestScope)的生命周期,以便在Web请求结束后自动处理DbContext。

您不再需要创建DbContext,因为Ninject会为您创建它并管理它的处置。