Difference between revisions of "Unit Of Work Pattern"

From Logic Wiki
Jump to: navigation, search
 
Line 7: Line 7:
 
[[File:UnitOfWork.JPG]]
 
[[File:UnitOfWork.JPG]]
  
 +
=== Interface ===
 +
<pre class="brush:csharp;">
 +
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();
 +
    }
 +
}
 +
</pre>
 +
 +
=== Implementation ===
 +
<pre class="brush:csharp;">
 +
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();
 +
        }
 +
    }
 +
}
 +
</pre>
  
 
See Also : [[Repository Pattern]]
 
See Also : [[Repository Pattern]]

Revision as of 11:44, 27 April 2017


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