在WCF服务库中处理DBContext

时间:2014-10-23 18:32:55

标签: .net entity-framework wcf dbcontext

我需要通过单击ASP.NET网站中的按钮来处理大量数据(500K +记录中的CRUD):) 我考虑过使用带有Entity Framework 6的WCF服务库。 只有一个edmx,所以只有一个" context"我想。

这是我的DAL atm:

public interface IBaseRepository<T> : IDisposable
{
    void Insert(T entity);
    void BulkInsert(IEnumerable<T> entities);
    void Delete(T entity);
    IQueryable<T> GetAll();
}

public class BaseRepository<T> : IBaseRepository<T> where T : class
{
    protected DbContext _context;
    public BaseRepository(DbContext dataContext)
    {
        _context = dataContext;
    }
    public BaseRepository()
    {
        _context = new MyDBContext();
    }
    public void Insert(T entity){/*CODE*/}
    public void Delete(T entity){/*CODE*/}
    public IQueryable<T> GetAll(){/*CODE*/}
    public void Dispose(){ this.Dispose(); }
}

public interface IProductRepository
{
    IQueryable<Product> GetAllProducts();
}

public class ProductRepository : BaseRepository<Product>, IProductRepository
{
    ProductRepository()
        : base()
    {}

    ProductRepository(DbContext dataContext)
        : base(dataContext)
    {}

    public IQueryable<Product> GetAllProducts()
    {
        return base.GetAll();
    }
}

将为每个实体重复最后一个代码(每个实体都有一个存储库)。

我想知道在哪里创建DBContext,我应该将它交给每个存储库中的构造函数,还是让BaseRepository构造器做它的事情? 如果我把它交给每个存储库,是否意味着我必须在BLL中创建它?我不想要:\

编辑:

我正在研究这个问题,但我从未使用过依赖注入框架..所以我不知道如何开始:\

我不确定我是否理解@MattSanders的意思。我知道我应该使用Unity之类的东西来为上层(Controller)进行依赖注入,但是我应该在哪里创建DBContext?我应该使用存储库的空构造函数(这意味着我将为每个存储库创建一个上下文),或者我应该将其作为参数交给每个构造函数(这样我可以使用相同的上下文所有存储库)?

1 个答案:

答案 0 :(得分:2)

如果您的代码依赖于Typed Repository的特定实例,那么接受构造函数中的dbContext以传递给可测试性的基类构造函数可能是有价值的。

在下面的示例中,如果您只想测试控制器功能(使用Mocked out DbSets的虚假上下文或者像Effort提供的内存实例),您可以选择提供模拟的存储库。

public class ProductController
{
    private readonly ProductRepository _productRepository;

    public ProductController (ProductRepository productRepository)
    {
        _productRepository = productRepository;
    }

    public void BuyProduct(int id)
    {
        // Example of something to do
    }
}

这绝对不是唯一的答案,但如果dbContext的依赖关系在基类构造函数中处理并且未公开,我想分享我对可测试性的限制。


编辑:以下是上述工作的链接: https://effort.codeplex.com/wikipage?title=Create%20a%20fake%20DbContext%20instance


编辑:

  

如果我将它交给每个存储库,那就意味着我必须创建它   在BLL?

我一直在使用带有IoC容器的工厂来检索我的存储库实例及其所有依赖项,如果你没有使用DI框架,它可以帮助解决这些类型的场景。

相关问题