Difference between revisions of "Unit Of Work Pattern"

From Logic Wiki
Jump to: navigation, search
(Usage)
 
Line 86: Line 86:
 
</pre>
 
</pre>
 
Payee is a repository not a DbSet. It's the main difference of using unit of work instead of context
 
Payee is a repository not a DbSet. It's the main difference of using unit of work instead of context
 +
-------------
 
See Also : [[Repository Pattern]]
 
See Also : [[Repository Pattern]]

Latest revision as of 11:32, 6 June 2017


Usage

UnitOfWork.JPG

Interface

using System;

namespace Spv.Api.Core.IDataAccess
{
    public interface IUnitOfWork : IDisposable
    {
        // for testability we user interfaces below. 
        // we can mock IUnitWork interface and the 
        // properties below in unit tests

        IDealRepository Deal { get; }
        IPayeeRepository Payee { get; }
        int Complete();
    }
}

Implementation

using Spv.Api.Core.IDataAccess;

namespace Spv.Api.Core.DataAccess
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly SpvDbContext _context;

        public UnitOfWork(SpvDbContext context)
        {
            _context = context;
            Payee = new PayeeRepository(_context);
            Deal = new DealRepository(_context);
        }


        public IPayeeRepository Payee { get; private set; }
        public IDealRepository Deal { get; private set; }

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

        public int Complete()
        {
            return _context.SaveChanges();
        }
    }
}

Usage

using System.Web.Mvc;
using Spv.Api.Core.IDataAccess;

namespace Spv.Api.Controllers
{
    public class HomeController : Controller
    {
        private readonly IUnitOfWork _unitOfWork;

        public HomeController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";
            ViewBag.Temp = _unitOfWork.Payee.Get(1).Name;
            return View();
        }
    }
}

Payee is a repository not a DbSet. It's the main difference of using unit of work instead of context


See Also : Repository Pattern