Unit Of Work Pattern

From Logic Wiki
Revision as of 11:44, 27 April 2017 by AliIybar (Talk | contribs)

Jump to: navigation, search


Usage

UnitOfWork.JPG

Interface

using System;

namespace Monky.API.Core.Data.Interfaces
{
    public interface IUnitOfWork : IDisposable
    {
        // for testability we user interfaces below. 
        // we can mock IUnitWork interface and the 
        // properties below in unit tests


        IPersonRepository UserMenus { get; }
        int Complete();
    }
}

Implementation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Monky.API.Core.Data.Interfaces;
using Monky.API.Core.Data.Repositories;

namespace Monky.API.Core.Data
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly MonkyDbContext _context;

        public UnitOfWork(MonkyDbContext context)
        {
            _context = context;
            UserMenus = new PersonRepository(_context);
            // ...
        }

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

        public IPersonRepository UserMenus { get; }
        // ...

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

See Also : Repository Pattern