Skip to main content

Architecture solution composting Repository Pattern, Unit Of Work, Dependency Injection, Factory Pattern and others

Project architecture is like garden, we plant the things in certain order and eventually they grow in similar manner. If things are planted well then they will all look(work) great and easier to manage. If they grow as cumbersome it would difficult to maintain and with time more problems would be happening in maintenance.

There is no any fixed or known approach to decide project architecture and specially with Agile Methodology. In Agile Methodology, we cannot predict how our end products will look like similarly we cannot say a certain architecture will fit well for entire development lifespan for project. So, the best thing is to modify the architecture as per our application growth. I understand that it sounds good but will be far more problematic with actual development. If it is left as it is then more problems will arise with time. Just think about moving plant vs a full grown tree.

Coming to technical side, In this article, I will be explaining about the various techniques that I have used and why that particular path has been taken.

The most dumbest yet the core part of any application is to save data. Whole application revolves around same. With growth of Object relational mapping(ORM), it is now a standard to map database tables as classes or we can say data models. In this particular architecture that we are going to create, data model will be playing central part of it.

It is always better to separate out data models rather then getting it associated with certain ORM. We might need to change ORM at any point as per need or certain things that used ORM provider does not provide. Also by keeping data models separate it could be used by other project in different way without hindering the current process. The approach could be called as Code first but these should be kept as a separate project.


As you see MyProject.Model is kept as separate project. There could be various models we are going to deal with. Like already told Data models, View models, Data Transfer Object or some internal business object model. All types of possible models meant to be kept over here.

So, now we know where to keep the different models associate with project. Before moving to DB layer let me introduce interface layer. The interfaces are like defining structure so that others can implement in there own way. Interfaces are great way to do Unit testing by mocking up object. The most important thing about interface is implementing dependency injection. In this way we won't be hard coding some specific class responsible to run application rather then dependent on interface. If the whole application is dependent on interface then we can change the definition of interfaces as per our different version of classes based on similar interface. Ex: Saving files, user can interact with cloud providers like Dropbox, OneDrive or any other. We can create our own interface and implement different version of classes as per available providers.

Again we will keep interface entirely in different layer so that we will be having the project specification at single place. This layer will also keep interfaces for any other features related to project like Business, services, factory or any core area like multiple caching, cloud access etc.

Let's move to DB layer, based on same I will be explaining related interfaces for MyProject.Interface.
In this one I will explaining all about Repositories, Unit of work.

Why repository pattern?
Repository pattern was created to have an abstraction from database so that people do not use Sql queries everywhere and other layers should not be aware of backend. With evolution of ORM and LINQ it make sense to avoid it but for me if anything is getting repeated then those should be kept as centralized place. Also sticking up with specific ORM does not sounds like good idea which may change in future.

The Repositories are created individually as per each data models. So, project can have lot of repository classes. To handle those multiple repositories Unit of work pattern is implement. For example, if multiple operations are done on database context then all of operation can be saved in a single transaction.

There are various ways to implement Repository and Unit of work. I will be giving walk through as per mine implementation with proper details why particular approach has been chosen.

Let's start with first stage where we need to create actual DbContext version for Entity Framework. I am keeping things less and simple for better clarity.

The simple DB context for just accepting connection string:

 internal sealed class MyProjectContext  
     : DbContext  
   {  
     public MyProjectContext()  
       : base("name=MyProjectEntities")  
     {  
     }  
     public MyProjectContext(string connectionString)  
       : base(connectionString)  
     {  
     }  
     protected override void OnModelCreating(DbModelBuilder modelBuilder)  
     {  
       // Configure mappings  
       new FluentMapping.FluentMapping(modelBuilder);  
     }  
   }  

The next thing we need to have an interface for DbContext creation:

   /// <summary>  
   /// Context factory for creation of context  
   /// </summary>  
   /// <typeparam name="TContext">Database context</typeparam>  
   public interface IContextFactory<out TContext>  
     where TContext : DbContext  
   {  
     /// <summary>  
     /// Creates new database context  
     /// </summary>  
     /// <returns>New Database context</returns>  
     TContext Create();  
   }  


The implementation for context factory
   /// <summary>  
   /// Context Factory for project  
   /// </summary>  
   public sealed class MyProjectContextFactory  
     : IContextFactory<DbContext>  
   {  
     /// <summary>  
     /// The connection string  
     /// </summary>  
     private readonly string _connectionString;  
     /// <summary>  
     /// Initializes a new instance of the <see cref="MyProjectContextFactory"/> class.  
     /// </summary>  
     /// <param name="connectionStringOrName">Name of the connection string or actual connection string.</param>  
     public MyProjectContextFactory(string connectionStringOrName)  
     {  
       _connectionString = connectionStringOrName;  
     }  
     /// <summary>  
     /// Creates new database context.  
     /// </summary>  
     /// <returns>DbContext: <see cref="MyProjectContext"/></returns>  
     public DbContext Create()  
     {  
       return new MyProjectContext(_connectionString);  
     }  
   }  

These are all for context related stuff. If you check the MyProjectContext class it is being set as internal for access specifier to restrict calls outside of DB layer. The only way to get context is through MyProjectContextFactory class which will get injected later on through IContextFactory.

After context we can jump into Repository creation. There are few steps which are implemented to reduce extra codes. Those are base class of repositories and interface for same. Each repositories are get accessed via interface that is why Repository's base class is created along with the interface for same.

Repository interface:

 /// <summary>  
   /// Base repository interface for interaction with DB model  
   /// </summary>  
   /// <typeparam name="TModel">Entity Type</typeparam>  
   public interface IRepository<TModel>  
     where TModel : class  
   {  
     /// <summary>  
     /// Gets the count.  
     /// </summary>  
     /// <value>Total rows count.</value>  
     int Count { get; }  
     /// <summary>  
     /// Alls this instance.  
     /// </summary>  
     /// <returns>All records from model</returns>  
     IQueryable<TModel> All();  
     /// <summary>  
     /// Gets model by id.  
     /// </summary>  
     /// <param name="id">The id.</param>  
     /// <returns>Entity</returns>  
     TModel GetById(object id);  
     /// <summary>  
     /// Gets objects via optional filter, sort order, and includes.  
     /// </summary>  
     /// <param name="filter">The filter.</param>  
     /// <param name="orderBy">The order by.</param>  
     /// <returns>IQueryable for model entity</returns>  
     IQueryable<TModel> Get(Expression<Func<TModel, bool>> filter = null, Func<IQueryable<TModel>,  
       IOrderedQueryable<TModel>> orderBy = null);  
     /// <summary>  
     /// Gets objects from database by filter.  
     /// </summary>  
     /// <param name="predicate">Specified filter</param>  
     /// <returns>IQueryable for model entity</returns>  
     IQueryable<TModel> Filter(Expression<Func<TModel, bool>> predicate);  
     /// <summary>  
     /// Gets objects from database with filtering and paging.  
     /// </summary>  
     /// <param name="filter">Specified filter.</param>  
     /// <param name="total">Returns the total records count of the filter.</param>  
     /// <param name="index">Page index.</param>  
     /// <param name="size">Page size.</param>  
     /// <returns>IQueryable for model entity</returns>  
     IQueryable<TModel> Filter(Expression<Func<TModel, bool>> filter, out int total, int index = 0, int size = 50);  
     /// <summary>  
     /// Gets the object(s) is exists in database by specified filter.  
     /// </summary>  
     /// <param name="predicate">Specified filter expression</param>  
     /// <returns><c>true</c> if contains the specified filter; otherwise, /c>.</returns>  
     bool Contains(Expression<Func<TModel, bool>> predicate);  
     /// <summary>  
     /// Find object by specified expression.  
     /// </summary>  
     /// <param name="predicate">Specified filter.</param>  
     /// <returns>Search result</returns>  
     TModel Find(Expression<Func<TModel, bool>> predicate);  
     /// <summary>  
     /// Create a new object to database.  
     /// </summary>  
     /// <param name="entity">A new object to create.</param>  
     /// <returns>Created object</returns>  
     void Create(TModel entity);  
     /// <summary>  
     /// Deletes the object by primary key  
     /// </summary>  
     /// <param name="id">Object key</param>  
     void Delete(object id);  
     /// <summary>  
     /// Delete the object from database.  
     /// </summary>  
     /// <param name="entity">Specified a existing object to delete.</param>  
     void Delete(TModel entity);  
     /// <summary>  
     /// Delete objects from database by specified filter expression.  
     /// </summary>  
     /// <param name="predicate">Specify filter.</param>  
     void Delete(Expression<Func<TModel, bool>> predicate);  
   }  

Repository base class:

 /// <summary>  
   /// Base repository implementation to interacting with database through ORM  
   /// </summary>  
   /// <typeparam name="TModel">The type of the model.</typeparam>  
   public class Repository<TModel>  
     : IRepository<TModel> where TModel : class  
   {  
     /// <summary>  
     /// DB context  
     /// </summary>  
     protected readonly DbContext DbContext;  
     /// <summary>  
     /// Gets the context.  
     /// </summary>  
     /// <typeparam name="T">Db Model</typeparam>  
     /// <returns></returns>  
     protected T GetContext<T>() where T  
       : class  
     {  
       return (T)Convert.ChangeType(DbContext, Type.GetTypeCode(typeof(T)));  
     }  
     /// <summary>  
     /// Initializes a new instance of the <see cref="Repository{TModel}"/> class.  
     /// </summary>  
     /// <param name="dbContext">The DB context.</param>  
     protected Repository(DbContext dbContext)  
     {  
       DbContext = dbContext;  
     }  
     /// <summary>  
     /// Gets the count.  
     /// </summary>  
     /// <value>Total rows count.</value>  
     public virtual int Count  
     {  
       get { return DbContext.Set<TModel>().Count(); }  
     }  
     /// <summary>  
     /// Alls this instance.  
     /// </summary>  
     /// <returns>All records from model</returns>  
     public virtual IQueryable<TModel> All()  
     {  
       return DbContext.Set<TModel>();  
     }  
     /// <summary>  
     /// Gets model by id.  
     /// </summary>  
     /// <param name="id">The id.</param>  
     /// <returns>DB Model</returns>  
     public virtual TModel GetById(object id)  
     {  
       return DbContext.Set<TModel>().Find(id);  
     }  
     /// <summary>  
     /// Gets objects via optional filter, sort order, and includes.  
     /// </summary>  
     /// <param name="filter">The filter.</param>  
     /// <param name="orderBy">The order by.</param>  
     /// <returns>IQueryable for model entity</returns>  
     public virtual IQueryable<TModel> Get(Expression<Func<TModel, bool>> filter = null,  
       Func<IQueryable<TModel>, IOrderedQueryable<TModel>> orderBy = null)  
     {  
       IQueryable<TModel> query = DbContext.Set<TModel>();  
       if (filter != null)  
       {  
         query = query.Where(filter);  
       }  
       return orderBy != null ? orderBy(query).AsQueryable() : query.AsQueryable();  
     }  
     /// <summary>  
     /// Gets objects from database by filter.  
     /// </summary>  
     /// <param name="predicate">Specified filter</param>  
     /// <returns>IQueryable for model entity</returns>  
     public virtual IQueryable<TModel> Filter(Expression<Func<TModel, bool>> predicate)  
     {  
       return DbContext.Set<TModel>().Where(predicate).AsQueryable();  
     }  
     /// <summary>  
     /// Gets objects from database with filtering and paging.  
     /// </summary>  
     /// <param name="filter">Specified filter.</param>  
     /// <param name="total">Returns the total records count of the filter.</param>  
     /// <param name="index">Page index.</param>  
     /// <param name="size">Page size.</param>  
     /// <returns>IQueryable for model entity</returns>  
     public virtual IQueryable<TModel> Filter(Expression<Func<TModel, bool>> filter, out int total, int index = 0, int size = 50)  
     {  
       var skipCount = index * size;  
       var resetSet = filter != null ? DbContext.Set<TModel>().Where(filter).AsQueryable()  
         : DbContext.Set<TModel>().AsQueryable();  
       resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size);  
       total = resetSet.Count();  
       return resetSet.AsQueryable();  
     }  
     /// <summary>  
     /// Gets the object(s) is exists in database by specified filter.  
     /// </summary>  
     /// <param name="predicate">Specified filter expression</param>  
     /// <returns><c>true</c> if contains the specified filter; otherwise, /c>.</returns>  
     public bool Contains(Expression<Func<TModel, bool>> predicate)  
     {  
       return DbContext.Set<TModel>().Any(predicate);  
     }  
     /// <summary>  
     /// Find object by specified expression.  
     /// </summary>  
     /// <param name="predicate">Specified filter.</param>  
     /// <returns>Search result</returns>  
     public virtual TModel Find(Expression<Func<TModel, bool>> predicate)  
     {  
       return DbContext.Set<TModel>().FirstOrDefault(predicate);  
     }  
     /// <summary>  
     /// Create a new object to database.  
     /// </summary>  
     /// <param name="entity">A new object to create.</param>  
     /// <returns>Created object</returns>  
     public virtual void Create(TModel entity)  
     {  
       DbContext.Set<TModel>().Add(entity);  
     }  
     /// <summary>  
     /// Deletes the object by primary key  
     /// </summary>  
     /// <param name="id">Object key</param>  
     public virtual void Delete(object id)  
     {  
       var entityToDelete = GetById(id);  
       Delete(entityToDelete);  
     }  
     /// <summary>  
     /// Delete the object from database.  
     /// </summary>  
     /// <param name="entity">Specified a existing object to delete.</param>  
     public virtual void Delete(TModel entity)  
     {  
       DbContext.Set<TModel>().Remove(entity);  
     }  
     /// <summary>  
     /// Delete objects from database by specified filter expression.  
     /// </summary>  
     /// <param name="predicate">Specify filter.</param>  
     public virtual void Delete(Expression<Func<TModel, bool>> predicate)  
     {  
       var entitiesToDelete = Filter(predicate);  
       foreach (var entity in entitiesToDelete)  
       {  
         DbContext.Set<TModel>().Remove(entity);  
       }  
     }  
   }  

The above interface and base class creates common logic to interact with data models so that basic functions can be avoided on each single repositories.

To access any data models respective repository with interface need to be created. Through these we can interact with domain models. Also any new function need to be added into these respective repository.

Ex:
IBookRepository.cs:

   /// <summary>  
   /// Interface to interact with <see cref="MyProject.Model.DataModel.Book"/> domain model.  
   /// </summary>  
   public partial interface IBookRepository  
        : IRepository<Book>  
   {  
   }  

BookRepository.cs

   /// <summary>  
   /// Interface for interacting with <see cref="MyProject.Model.DataModel.BookRepository"/>  
   /// </summary>  
      public partial class BookRepository  
           : Repository<MyProject.Model.DataModel.Book>,  
            MyProject.Interface.Repository.IBookRepository  
      {  
     /// <summary>  
     /// Initializes a new instance of the <see cref="BookRepository"/> class.  
     /// </summary>  
     /// <param name="dbContext">The database context.</param>  
     public BookRepository(DbContext dbContext)  
       : base(dbContext)  
     {  
     }  
      }  

As per each model these similar repository and interfaces need to be created. It becomes little cumbersome to keep adding these interfaces and respective classes for each models. I have created a T4 which generates basic class and interface according to models.

This is it as per repository. Now we are going to create Unit of work to handle to create instance of these repository interface and classes.

There would be a generic Unit of work interface and class which need to derived by project specific Unit of work. This creates another abstraction to implement Unit of work as repositories are project specific. This can be extended if we have more the one repository system.

IUnitOfWork.cs

   /// <summary>  
   /// Generic version of Unit Of Work.  
   /// </summary>  
   public interface IUnitOfWork : IDisposable  
   {  
     /// <summary>  
     /// Regenerates the context.  
     /// </summary>  
     void RegenerateContext();  
     /// <summary>  
     /// Saves Context changes.  
     /// </summary>  
     void Save();  
   }  

The above can be extended to specific transaction classes. The dispose function is written over here to handle context and also this is the key to share context among all repositories. The other thing need to noted out is the context is getting initialized by passing IContextFactory which will be passed and initialized on later stage.

 /// <summary>  
   /// Unit of work implementation for having single instance of context and doing DB operation as transaction  
   /// </summary>  
   /// <typeparam name="TContext">The type of the context.</typeparam>  
   public abstract class UnitOfWork<TContext> : IUnitOfWork  
     where TContext : DbContext  
   {  
     /// <summary>  
     /// DB context  
     /// </summary>  
     private TContext _dbContext;  
     /// <summary>  
     /// The DB context factory  
     /// </summary>  
     private readonly IContextFactory<TContext> _dbContextFactory;  
     /// <summary>  
     /// Initializes a new instance of the <see cref="UnitOfWork{TContext}"/> class.  
     /// </summary>  
     /// <param name="dbContextFactory">The db context factory.</param>  
     protected UnitOfWork(IContextFactory<TContext> dbContextFactory)  
       : this(dbContextFactory.Create())  
     {  
       _dbContextFactory = dbContextFactory;  
     }  
     /// <summary>  
     /// Initializes a new instance of the <see cref="UnitOfWork{TContext}"/> class.  
     /// </summary>  
     /// <param name="context">The context.</param>  
     protected UnitOfWork(TContext context)  
     {  
       _dbContext = context;  
     }  
     /// <summary>  
     /// Gets the context.  
     /// </summary>  
     /// <value>The context.</value>  
     public virtual TContext Context  
     {  
       get  
       {  
         return _dbContext;  
       }  
     }  
     /// <summary>  
     /// Regenerates the context.  
     /// </summary>  
     /// <remarks>WARNING: Calling with dirty context will save changes automatically</remarks>  
     public void RegenerateContext()  
     {  
       if (_dbContext != null)  
       {  
         Save();  
       }  
       _dbContext = _dbContextFactory.Create();  
     }  
     /// <summary>  
     /// Saves Context changes.  
     /// </summary>  
     public void Save()  
     {  
       Context.SaveChanges();  
     }  
     #region " Dispose "  
     /// <summary>  
     /// To detect redundant calls  
     /// </summary>  
     private bool _disposedValue;  
     /// <summary>  
     /// Dispose the object  
     /// </summary>  
     /// <param name="disposing">IsDisposing</param>  
     protected virtual void Dispose(bool disposing)  
     {  
       if (!_disposedValue)  
       {  
         if (disposing)  
         {  
           if (_dbContext != null)  
           {  
             _dbContext.Dispose();  
           }  
         }  
       }  
       _disposedValue = true;  
     }  
     #region " IDisposable Support "  
     /// <summary>  
     /// Dispose the object  
     /// </summary>  
     public void Dispose()  
     {  
       Dispose(true);  
       GC.SuppressFinalize(this);  
     }  
     #endregion " IDisposable Support "  
     #endregion " Dispose "  
   }  

Project specific Unit of work. If you check the class it is kind of hard coding the interface with related class which is not good. Instead of this service locator pattern or property dependency injection could be used but with this approach we have all repository instances at one place and also it is kind of lazy loading so that all instances does not get initialized at once. Also we are reducing a code much in this implementation.
Again, the instance creation of repository could be done with T4 which can be found in solution by using partial class.

 public sealed partial class MyProjectUnitOfWork  
     : UnitOfWork<DbContext>, IMyProjectUnitOfWork  
   {  
     public MyProjectUnitOfWork(IContextFactory<DbContext> contextFactory)  
       : base(contextFactory)  
     {  
     }  
     /// <summary>  
     /// BookRepository holder  
     /// </summary>  
     private MyProject.DB.Repository.BookRepository _bookRepository;  
     /// <summary>  
     /// Gets the BookRepository repository.  
     /// </summary>  
     /// <value>  
     /// The BookRepository repository.  
     /// </value>  
     MyProject.Interface.Repository.IBookRepository IMyProjectUnitOfWork.BookRepository  
     {  
       get  
       {  
         return _bookRepository =  
         _bookRepository ?? new MyProject.DB.Repository.BookRepository(Context);  
       }  
     }  
   }  

After all these, we are set with required architecture. Now, we just need to get it initialized with dependency injection under Web layer. Over here I am using Ninject for same. It can be installed via NuGet Ninject.MVC version package. It creates a NinjectWebCommon class under App_Start folder and under RegisterServices function we need to set dependency injection.

As you see, IContextFactory mapped with MyProjectContextFactory for context initialization and similarly UnitOfWork is initialized. Also this mapping will automatically create context and get disposed as per user request without taking overhead of initialization and disposing of object on our head.

       kernel.Bind<IContextFactory<DbContext>>()  
         .ToConstructor(ctxFac => new MyProjectContextFactory  
           (ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString));  
       kernel.Bind<IMyProjectUnitOfWork>().To<MyProjectUnitOfWork>();  

Before using them let's create a base class on MVC Controller to avoid variable creation every time.
If you see we just have created constructor  and having parameter of interface. This way we are avoiding any specific class and later on without changing entire application class definition can be simply changed by changing mapping that we did on Ninject Bind function.

BaseController:

  /// <summary>  
   /// Base controller for the application  
   /// </summary>  
   public abstract class BaseController  
     : Controller  
   {  
     /// <summary>  
     /// Gets my project unit of work.  
     /// </summary>  
     /// <value>  
     /// My project unit of work.  
     /// </value>  
     protected IMyProjectUnitOfWork MyProjectUnitOfWork { get; private set; }  
     /// <summary>  
     /// Initializes a new instance of the <see cref="BaseController"/> class.  
     /// </summary>  
     /// <param name="unitOfWork">The unit of work.</param>  
     public BaseController(IMyProjectUnitOfWork unitOfWork)  
     {  
       MyProjectUnitOfWork = unitOfWork;  
     }  
   }  

Final step, inherit any created controller with BaseController and create constructor with IMyProjectUnitOfWork which initializes property of base controller by initializing base class constructor.
Now if you see under Index action, repository and unit of work is used in simple and clean way without making much noise in code.

 public class HomeController : BaseController  
   {  
     public HomeController(IMyProjectUnitOfWork unitOfWork)  
       : base(unitOfWork)  
     {  
     }  
     public ActionResult Index()  
     {  
       MyProjectUnitOfWork.BookRepository.Create(new Model.DataModel.Book  
       {  
         BookTitle = "C#",  
         ISBN = "123",  
         PublisherName = "NA"  
       });  
       if (MyProjectUnitOfWork.BookRepository.Count == 0)  
       {  
         MyProjectUnitOfWork.Save();  
       }  
       return View();  
     }  
   }  

The entire code can be found on https://www.dropbox.com/s/41gakohw5r7030z/MyProject.zip?dl=0.

Popular posts from this blog

LDAP with ASPNet Core Identity in MVC Core

Lightweight Directory Access Protocol (LDAP), the name itself explain it. An application protocol used over an IP network to access the distributed directory information service.

AspNet Identity Core is a new offering from Microsoft in replacement of AspNet Identity for managing users.

In this tutorial, we would be looking for implementing LDAP with AspNet Identity Core to allow users to be able to log in through AD or AspNet Identity Core members.

The first and foremost thing is to add references for consuming LDAP. This has to be done by adding reference from Global Assembly Cache (GAC) into project.json

"frameworks": { "net461": { "frameworkAssemblies": { "System.DirectoryServices": "4.0.0.0", "System.DirectoryServices.AccountManagement": "4.0.0.0" } } },
These System.DirectoryServices and System.DirectoryServices.AccountManagement references are used to consume LDAP functiona…

Configuring Ninject, Asp.Net Identity UserManager, DataProtectorTokenProvider with Owin

It can be bit tricky to configure both Ninject and Asp.Net Identity UserManager if some value is expected from DI to configure UserManager. We will look into configuring both and also use OwinContext to get UserManager.

As usual, all configuration need to be done on Startup.cs. It is just a convention but can be used with different name, the important thing is to decorate class with following attribute to make it Owin start-up:

[assembly: OwinStartup(typeof(MyProject.Web.Startup))]
Ninject configuration

Configuring Ninject kernel through method which would be used to register under Owin.

Startup.cs
public IKernel CreateKernel() { var kernel = new StandardKernel(); try { //kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); // TODO: Put any other injection which are required. return kernel; } catch { kernel.Dispose(); throw; }…