Repository + UnitOfWork pattern for entity framework

﹥>﹥吖頭↗ 提交于 2019-12-04 03:19:57

I used this blog as a really good starting point:

http://www.primaryobjects.com/CMS/Article122.aspx

It starts at the VERY beginning, and provides source code at the end for you. It also uses StructureMap, so it might be somewhat familiar to you.

I would recommend the NCommon framework. You can find a blog about it here: http://www.codeinsanity.com/

I wrote an article last year about writing LINQ enabled repositories that can be faked easily for unit testing and works well with dependency injection. Here is the article. In short the article describes a unit of work that mimics the LINQ to SQL DataContext and wraps an IDataMapper interface that abstracts the actual O/RM tool. The unit of work contains properties of type Repository<TEntity> such as Repository<Customer> or Repository<Order> and the repository class implements IQueryable<T>, which allows you to LINQ over it.

The IDataMapper is a simple interface that looks like this:

public interface IDataMapper : IDisposable
{
    Repository<T> GetRepository<T>() where T : class;

    void Save();
}

The solution described in the article is designed to be unit test friendly and DI friendly. In fact, the only configuration you need is the following:

string northwindConnection = GetConStr("Northwind");

container.RegisterSingle<IUnitOfWorkFactory<NorthwindUnitOfWork>>(
    new LinqToSqlNorthwindUnitOfWorkFactory(northwindConnection));

container.RegisterSingle<IUnitOfWorkFactory<SalesUnitOfWork>>(
    new EntityFrameworkSalesUnitOfWorkFactory());

If you already have unit of work and repositories and you are using StructureMap so where is the problem?

You can simply configure your classes as:

ObjectFactory.Configure(x => x.For<IUnitOfWork>()
                              .HybridHttpOrThreadLocalScoped()
                              .Use<EFUnitOfWork>());

And you can use dependency injection to pass unit of work to repositories.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!