IUnitOfWork how to use - best practice

倾然丶 夕夏残阳落幕 提交于 2019-12-05 17:51:34

Dmitry is right. Here is a sample implementation of a Unit of work. The benefit here is that the unit of work pattern coordinates the work of the multiple repositories by enforcing a single database context class shared by all of them.

This is a good resource for beginning to understand how these patterns can be used together. It is valid for both MVC and web Forms development. Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application

public class UnitOfWork : IDisposable
{
    private DbContext _context;
    private PersonRepository _personRepository;
    private CompanyRepository _companyRepository;

    public UnitOfWork(DbContext context)
    {
        this._context = context;
    }

    public void Commit()
    {
        _context.SaveChanges();
    }

    // We lazy-load our repositories...
    public PersonRepository PersonRepository 
    {
        get
        {
            if (this._personRepository == null)
            {
                this._personRepository = new PersonRepository(context);
            }
            return _personRepository;
        }
    }

    public CompanyRepository 
    {
        get
        {
            if (this._companyRepository == null)
            {
                this._companyRepository = new CompanyRepository(context);
            }
            return _companyRepository;
        }
    }

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