CRUD Operations Using the Generic Repository Pattern and Dependency Inversion Principle With IoC Container and DI in MVC

This article introduces use of the Generic Repository Pattern and Dependency Inversion Principle With IoC Container and DI in MVC for CRUD Operations. The user interface design in this application uses Bootstrap CSS and JavaScript.

Table of Contents

  1. Introduction
  2. Dependency Inversion Principle (DIP)

      a. Real-Life Example
      b. Practical Example without DIP
      c. Practical Example with DIP

  3. Inversion of Control (IoC) Pattern
  4. Dependency Injection (DI)

      a. Tight Coupling
      b. Loose Coupling

  5. Dependency Injection (DI) Container
  6. CRUD operations Application Design

      a. Define Entities in Application
      b. Define Context Class
      c. Define Mapping of Entities
      d. Create Generic Repository
      e. Create Service for User Operations

  7. An MVC Application Using the IoC and DI

      a. Ninject Dependency Injection Container
      b. CRUD Operations Model and Controller
      c. Create / Edit User View
      d. User List View
      e. User Detail View
      f. Delete User

  8. Conclusion
  9. Download
Introduction

A software developer writes a lot of code that is tightly coupled and when complexity grows the code will eventually deteriorate into spaghetti code, in other words application design being a bad design. A bad design that has one of the following causes.
  1. Rigid: A design is rigid if it cannot be easily changed. A single change is heavily dependent on another module so this change causes a cascade of changes that couldn't be predicted, the impact of change could not be estimated.

  2. Fragile: A simple change to one part of the application leads to failures in another part of it that appears completely unrelated. Fixing those problems leads to even more problems.

  3. Immobile: When the desirable parts of the design are highly dependent upon other details that are not desired and that is why one part of the application could not be used in another application.

    Causes in bad design application
    Figure 1.1: Causes in bad design application
The Dependency Inversion Principle is a solution for all these causes, that's why in this article I explain it. This article basically focuses on DIP, IoC, DI and DI containers so before diving into these, I just want to provide a small introduction in this section.

The Dependency Inversion Principle (DIP) is a software design principle that is the last principle of SOLID while Inversion of Control (IoC) is a software design pattern. Here I used two terms, one is a principle and the other is a pattern. So what is the basic difference between these?
  1. Software Design Principle: Software Design Principles represent a set of guidelines that help us to avoid having a bad design. These are less about specific languages or paradigms and more generally "Don't Repeat Yourself" (DRY); the DRY principle is true for all programming.

  2. Software Design Pattern: Software Design Patterns are a general reusable solution to a commonly occurring problem within a given context in software design. These are common solutions for object-oriented programming problems. Like the Singleton Pattern and Factory Pattern.

Dependency Inversion Principle (DIP)

It is the fifth principle of SOLID where “D” stands for Dependency Inversion Principle. Its main goal is decoupling software modules, in other words software design should be loosely coupled instead of tightly coupled. The principle states:
  1. High-level modules should not depend upon low-level modules. Both should depend upon abstractions.
  2. Abstractions should not depend upon details. Details should depend upon abstractions.

In short the higher-level module defines an interface and lower-level module implements that interface. To explain this sentence we use a real-life example.

Real-Life Example

Suppose you are sitting on your desk. Your desk has some gadgets, like your development machine (LCD Monitor or Laptop) and mobile phone. The LCD Monitor has a cable that connects from the electric port (power cable) and the same as the mobile phone that also has a charging cable that also connects to an electric port. You could see that both devices connect from the electric port so the question occurs of who defined the port, your device or the cable? You will say that the devices define the port, in other words we don't purchase devices depending on port while the port is designed dependent on devices and the cable is just an interface that connects both devices and the port so you could say that a high-level module doesn't depend on the low-level module but both should be dependent on abstraction.

Practical Example without DIP

To understand DIP, we use an example that explains how an error log can manage an application. There are two types of log management, the first one is via text file and the other is by using the event viewer. We create a high-level Operation class for error log entry. We create two interfaces, one is IEventViewerLogger and the other is IFileLogger interface. The IEventViewerLogger interface is implemented by the EventViewerLogger class while the IFileLogger interface is implemented by the FileLogger class.

The preceding Figure 1.2 shows that a high-level Operation class depends on the interface. We create an instance of each interface in this class and assign an appropriate object to each instance and use the operation accordingly. This means that a high-level module Operation class depends on the low-level module such as interfaces. Now suppose we want to add a new logger, such as a Database logger. Then we need to add a new interface and that's why the Operation class needs to care for all the interfaces and that's a violation of the Dependency Inversion Principle.

without Dependency Inversion Principle
Figure 1.2: without Dependency Inversion Principle

Practical Example of DIP

DIP states that a high-level module should not depend on a low-level module, both should be dependent on abstraction. To implement this principle we create an ILogger interface that is defined by a high-level module, in other words by an operation class and implemented by low-level modules, both EventViewerLogger and FileLogger classes. So when we add a new Logger, such as a database logger, then we don't need to update the Operation class.

Example of Dependency Inversion Principle
Figure 1.3: Example of Dependency Inversion Principle

It's a basic introduction to the Dependency Inversion Principle. If you are looking for code for this example then you can visit: Constructor Dependency Injection Pattern Implementation in C#. As I mention in this article that the software design principle is a guideline, in other words  DIP doesn't tell us how to solve the preceding problem. If we want to understand how to solve the preceding problem then we need to follow a software design pattern and move onto Inversion of Control.

Inversion of Control (IoC) Pattern

DIP is a software design principle that defines a guideline to solve a problem while IoC is a software design pattern that defines how to solve the problem. In other words the IoC is the pattern by which we can practically implement DIP in software development. Let's see an example.

In the previous error logger example, we define interfaces and implement them in classes. DIP states that a High-level Module should not be depend on a low-level module, that means we define the interface according to a high-level module Operation Class and implemented on a low-level module classes. The IoC is inverting the control of something switching control. In other words an outside module or class is responsible for creating an object of the class instead of directly creating the object of the low-level module class in the high-level module class so we can say that an IoC is an abstraction on which both high-level and low-level modules depend and it inverts the control flow.

In short we can say that IoC is used to invert the control flow of the application and an application module interacts with another module via interface and application classes object are created from one class.

DIP implementation
Figure 1.4: DIP implementation

Dependency Injection (DI)

Dependency Injection (DI) is a type of IoC, it is a pattern where objects are not responsible for creating their own dependencies. Dependency injection is a way to remove hard-coded dependencies among objects, making it easier to replace an object's dependencies, either for testing (using mock objects in unit test) or to change run-time behaviour.

Before understanding Dependency Injection, you should be familiar with the two concepts of Object Oriented Programming, one is tight coupling and another is loose coupling, so let's see each one by one.

Tight Coupling: When a class is dependent on a concrete dependency, it is said to be tightly coupled to that class. A tightly coupled object is dependent on another object; that means changing one object in a tightly coupled application often requires changes to a number of other objects. It is not difficult when an application is small but in an enterprise level application, it is too difficult to make the changes.

Loose Coupling: It means two objects are independent and an object can use another object without being dependent on it. It is a design goal that seeks to reduce the inter-dependencies among components of a system with the goal of reducing the risk that changes in one component will require changes in any other component.

Now in short, Dependency Injection is a pattern that makes objects loosely coupled instead of tightly coupled. Generally we create a concrete class object in the class we require the object and bind it in the dependent class but DI is a pattern where we create a concrete class object outside this high-level module or dependent class.

There are three types of dependency injections:

  1. Constructor Dependency Injection
  2. Setter Dependency Injection
  3. Interface Dependency Injection

In this article we will use Constructor Dependency Injection. This is the most commonly used Dependency Injection Pattern in Object Oriented Programming. The Constructor Dependency Injection uses a parameter to inject dependencies so there is normally one parameterized constructor always. So in this constructor dependency, the object has no default constructor and you need to pass specified values at the time of creation to initiate the object. You can say that your design is loosely coupled with the use of constructor dependency injection.

Dependency Injection (DI) Container

The Dependency Injection Container is a framework to create dependencies and inject them automatically when required. It automatically creates objects based on requests and injects them when required. It helps us split our application into a collection of loosely-coupled, highly-cohesive pieces and then glue them back together in a flexible manner. By DI container, our code will become easier to write, reuse, test and modify. In this article we will use a Niject DI Container.

CRUD operations Application Design

We create four projects in a solution to implement DIP with generic repository pattern. These are:

  1. Ioc.Core (class library)
  2. Ioc.Data (class library)
  3. Ioc.Service (class library)
  4. Ioc.Web (web application)

    Application Project Structure
    Figure 1.5: Application Project Structure

Define Entities in Application

In this article, we are working with the Entity Framework Code First Approach so the project Ioc.Core contains entities that are necessary in the application's database. In this project, we create three entities, one is the BaseEntity class that has common properties that will be inherited by each entity and the other are User and UserProfile entities. Let's see each entity. The following is a code snippet for the BaseEntity class.

  1. using System;  
  2. namespace Ioc.Core  
  3. {  
  4.   public abstract class BaseEntity  
  5.     {  
  6.       public Int64 ID { getset; }  
  7.       public DateTime AddedDate { getset; }  
  8.       public DateTime ModifiedDate { getset; }  
  9.       public string IP { getset; }  
  10.     }  
  11. }  
The User and UserProfile entities have a one-to-one relationship. One User can have only one profile.

Relationship between User and UserProfile Entities
Figure 1.6: Relationship between User and UserProfile Entities

Now, we create a User entity under the Data folder of the Ioc.Core project that inherits from the BaseEntity class. The following is a code snippet for the User entity.
  1. using System;  
  2. namespace Ioc.Core.Data  
  3. {  
  4.    public class User : BaseEntity  
  5.     {  
  6.        public string UserName { getset; }  
  7.        public string Email { getset; }  
  8.        public string Password { getset; }  
  9.        public virtual UserProfile UserProfile { getset; }  
  10.     }  
  11. }  
Now, we create a UserProfile entity under the Data folder of the Ioc.Core project that inherits from the BaseEntity class. The following is a code snippet for the UserProfile entity.
  1. using System;  
  2. namespace Ioc.Core.Data  
  3. {  
  4.   public class UserProfile : BaseEntity  
  5.     {  
  6.       public string FirstName { getset; }  
  7.       public string LastName { getset; }  
  8.       public string Address { getset; }        
  9.       public virtual User User { getset; }  
  10.     }  
  11. }  
Define Context Class

The Ioc.Data project contains DataContext, User and UserProfile entities Mapping and Repository. The ADO.NET Entity Framework Code First data access approach requires us to create a data access context class that inherits from the DbContext class so we create an interface IDbContext that inherited by context class IocDbContext (IocDbContext.cs) class. In this class, we override the OnModelCreating() method. This method is called when the model for a context class (IocDbContext) has been initialized, but before the model has been locked down and used to initialize the context such that the model can be further configured before it is locked down. First create an IDbContext interface and the following code snippet for it.
  1. using System.Data.Entity;  
  2. using Ioc.Core;  
  3. namespace Ioc.Data  
  4. {  
  5.    public interface IDbContext  
  6.     {  
  7.         IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity;  
  8.         int SaveChanges();  
  9.     }  
  10. }  
Now, create the IocDbContext class and the following code snippet for it.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using System.Data.Entity.ModelConfiguration;  
  5. using System.Linq;  
  6. using System.Reflection;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9. using Ioc.Core;  
  10.   
  11. namespace Ioc.Data  
  12. {  
  13.     public class IocDbContext : DbContext, IDbContext  
  14.     {  
  15.         public IocDbContext()  
  16.             : base("name=DbConnectionString")  
  17.         {  
  18.         }  
  19.   
  20.         protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  21.         {  
  22.               
  23.             var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()  
  24.             .Where(type => !String.IsNullOrEmpty(type.Namespace))  
  25.             .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));  
  26.             foreach (var type in typesToRegister)  
  27.             {  
  28.                 dynamic configurationInstance = Activator.CreateInstance(type);  
  29.                 modelBuilder.Configurations.Add(configurationInstance);  
  30.             }  
  31.          base.OnModelCreating(modelBuilder);  
  32.         }  
  33.   
  34.         public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity  
  35.         {  
  36.             return base.Set<TEntity>();  
  37.         }  
  38.     }  
  39. }  
As you know, the EF Code First approach follows convention over configuration, so in the constructor, we just pass the connection string name, the same as an App.Config file and it connects to that server. In theOnModelCreating() method, we used reflection to map an entity to its configuration class in this specific project.

Define Mapping of Entities

Now, we define the configuration for the User and UserProfile entities that will be used when the database table will be created by the entity. The configuration defines the class library project Ioc.Data under the Mapping folder. Now create the configuration classes for the entity. For the User entity, we create the UserMap class and for the UsrProfile entity, create the UserProfileMap class.

The following is a code snippet for the UserMap class.
  1. using System.Data.Entity.ModelConfiguration;  
  2. using Ioc.Core.Data;  
  3.   
  4. namespace Ioc.Data.Mapping  
  5. {  
  6.    public class UserMap :EntityTypeConfiguration<User>   
  7.     {  
  8.        public UserMap()  
  9.        {  
  10.            //key  
  11.            HasKey(t => t.ID);  
  12.            //properties  
  13.            Property(t => t.UserName).IsRequired();  
  14.            Property(t => t.Email).IsRequired();  
  15.            Property(t => t.Password).IsRequired();  
  16.            Property(t => t.AddedDate).IsRequired();  
  17.            Property(t => t.ModifiedDate).IsRequired();  
  18.            Property(t => t.IP);  
  19.            //table  
  20.            ToTable("Users");  
  21.        }  
  22.     }  
  23. }  
The following is a code snippet for the UserProfileMap class.
  1. using System.Data.Entity.ModelConfiguration;  
  2. using Ioc.Core.Data;  
  3.   
  4. namespace Ioc.Data.Mapping  
  5. {  
  6.    public class UserProfileMap : EntityTypeConfiguration<UserProfile>  
  7.     {  
  8.        public UserProfileMap()  
  9.        {  
  10.            //key  
  11.            HasKey(t => t.ID);  
  12.            //properties             
  13.            Property(t => t.FirstName).IsRequired().HasMaxLength(100).HasColumnType("nvarchar");  
  14.            Property(t => t.LastName).HasMaxLength(100).HasColumnType("nvarchar");  
  15.            Property(t => t.Address).HasColumnType("nvarchar");  
  16.            Property(t => t.AddedDate).IsRequired();  
  17.            Property(t => t.ModifiedDate).IsRequired();  
  18.            Property(t => t.IP);  
  19.            //table  
  20.            ToTable("UserProfiles");  
  21.            //relation            
  22.            HasRequired(t => t.User).WithRequiredDependent(u => u.UserProfile);  
  23.        }         
  24.     }  
  25. }  
Create Generic Repository

The Repository pattern is intended to create an abstraction layer between the data access layer and the business logic layer of an application. It is a data access pattern that prompts a more loosely coupled approach to data access. We create the data access logic in a separate class, or set of classes, called a repository, with the responsibility of persisting the application's business model.

Now, we create a generic repository interface and class. This generic repository has all CRUD operations methods. This repository contains a parameterized constructor with a parameter as Context so when we create an instance of the repository, we pass a context so that all the repositories for each entity has the same context. We are using the saveChanges() method of the context. The following is a code snippet for the Generic Repository interface.
  1. using System.Linq;  
  2. using Ioc.Core;  
  3.   
  4. namespace Ioc.Data  
  5. {  
  6.     public interface IRepository<T> where T : BaseEntity  
  7.     {  
  8.         T GetById(object id);  
  9.         void Insert(T entity);  
  10.         void Update(T entity);  
  11.         void Delete(T entity);  
  12.         IQueryable<T> Table { get; }  
  13.     }  
  14. }  
The following is a code snippet for the Generic Repository class that implements the IRepository<T> interface.
  1. using System;  
  2. using System.Data.Entity;  
  3. using System.Data.Entity.Validation;  
  4. using System.Linq;  
  5. using Ioc.Core;  
  6.   
  7. namespace Ioc.Data  
  8. {  
  9.    public class Repository<T> : IRepository<T> where T: BaseEntity  
  10.     {  
  11.         private readonly IDbContext _context;  
  12.         private IDbSet<T> _entities;  
  13.   
  14.         public Repository(IDbContext context)  
  15.         {  
  16.             this._context = context;  
  17.         }  
  18.   
  19.         public T GetById(object id)  
  20.         {  
  21.             return this.Entities.Find(id);  
  22.         }  
  23.   
  24.         public void Insert(T entity)  
  25.         {  
  26.             try  
  27.             {  
  28.                 if (entity == null)  
  29.                 {  
  30.                     throw new ArgumentNullException("entity");  
  31.                 }  
  32.                 this.Entities.Add(entity);  
  33.                 this._context.SaveChanges();  
  34.             }  
  35.             catch (DbEntityValidationException dbEx)  
  36.             {  
  37.                 var msg = string.Empty;  
  38.   
  39.                 foreach (var validationErrors in dbEx.EntityValidationErrors)  
  40.                 {  
  41.                     foreach (var validationError in validationErrors.ValidationErrors)  
  42.                     {  
  43.                         msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;  
  44.                     }  
  45.                 }  
  46.   
  47.                 var fail = new Exception(msg, dbEx);                  
  48.                 throw fail;  
  49.             }  
  50.         }  
  51.   
  52.         public void Update(T entity)  
  53.         {  
  54.             try  
  55.             {  
  56.                 if (entity == null)  
  57.                 {  
  58.                     throw new ArgumentNullException("entity");  
  59.                 }  
  60.                 this._context.SaveChanges();  
  61.             }  
  62.             catch (DbEntityValidationException dbEx)  
  63.             {  
  64.                 var msg = string.Empty;  
  65.                 foreach (var validationErrors in dbEx.EntityValidationErrors)  
  66.                 {  
  67.                     foreach (var validationError in validationErrors.ValidationErrors)  
  68.                     {  
  69.                         msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);  
  70.                     }  
  71.                 }  
  72.                 var fail = new Exception(msg, dbEx);                  
  73.                 throw fail;  
  74.             }  
  75.         }  
  76.   
  77.         public void Delete(T entity)  
  78.         {  
  79.             try  
  80.             {  
  81.                 if (entity == null)  
  82.                 {  
  83.                     throw new ArgumentNullException("entity");  
  84.                 }  
  85.                 this.Entities.Remove(entity);  
  86.                 this._context.SaveChanges();  
  87.             }  
  88.             catch (DbEntityValidationException dbEx)  
  89.             {  
  90.                 var msg = string.Empty;  
  91.   
  92.                 foreach (var validationErrors in dbEx.EntityValidationErrors)  
  93.                 {  
  94.                     foreach (var validationError in validationErrors.ValidationErrors)  
  95.                     {  
  96.                         msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);  
  97.                     }  
  98.                 }  
  99.                 var fail = new Exception(msg, dbEx);                  
  100.                 throw fail;  
  101.             }  
  102.         }  
  103.   
  104.         public virtual IQueryable<T> Table  
  105.         {  
  106.             get  
  107.             {  
  108.                 return this.Entities;  
  109.             }  
  110.         }  
  111.   
  112.         private IDbSet<T> Entities  
  113.         {  
  114.             get  
  115.             {  
  116.                 if (_entities == null)  
  117.                 {  
  118.                     _entities = _context.Set<T>();  
  119.                 }  
  120.                 return _entities;  
  121.             }  
  122.         }  
  123.     }  
  124. }  
Create Service for User Operations

To implement DIP with DI we create a service for the user entity that the service communicates with the UI and data access logic. Since DIP states that a high-level module should not depend on a low-level module we define an IUsesService interface in the Ioc.Service project depending on what we need on the UI to do the CRUD operations. The following code snippet is for IUserService.
  1. using System.Linq;  
  2. using Ioc.Core.Data;  
  3.   
  4. namespace Ioc.Service  
  5. {  
  6.    public interface IUserService  
  7.     {  
  8.        IQueryable<User> GetUsers();  
  9.        User GetUser(long id);  
  10.        void InsertUser(User user);  
  11.        void UpdateUser(User user);  
  12.        void DeleteUser(User user);  
  13.     }  
  14. }  
Now, we create a concrete UserService class that implemented the IUserService interface to do CRUD operations on both User and UserProfile entities using generic repository. The following code snippet is for the UserService class in the same project.
  1. using System.Linq;  
  2. using Ioc.Core.Data;  
  3. using Ioc.Data;  
  4.   
  5. namespace Ioc.Service  
  6. {  
  7. public class UserService : IUserService  
  8. {  
  9. private IRepository<User> userRepository;  
  10. private IRepository<UserProfile> userProfileRepository;  
  11.   
  12. public UserService(IRepository<User> userRepository, IRepository<UserProfile> userProfileRepository)  
  13. {  
  14. this.userRepository = userRepository;  
  15. this.userProfileRepository = userProfileRepository;  
  16. }  
  17.   
  18. public IQueryable<User> GetUsers()  
  19. {  
  20. return userRepository.Table;  
  21. }  
  22.   
  23. public User GetUser(long id)  
  24. {  
  25. return userRepository.GetById(id);  
  26. }  
  27.   
  28. public void InsertUser(User user)  
  29. {  
  30. userRepository.Insert(user);  
  31. }  
  32.   
  33. public void UpdateUser(User user)  
  34. {  
  35. userRepository.Update(user);  
  36. }  
  37.   
  38. public void DeleteUser(User user)  
  39. {  
  40. userProfileRepository.Delete(user.UserProfile);  
  41. userRepository.Delete(user);  
  42. }  
  43. }  
  44. }  
An MVC Application Using the IoC and DI

In this section we use a fourth project, Ioc.Web, to design the user interface so that we can do CRUD operations on both User and UserProfile entities.

Ninject Dependency Injection Container

The Ninject is a lightweight dependency injection framework for .NET applications. It helps us split our application into a collection of loosely-coupled, highly-cohesive pieces and then glue them back together in a flexible manner. By using Ninject to support our application's architecture, our code will become easier to write, reuse, test and modify. You can learn more about it from: http://www.ninject.org/.

Our Hero Ninject Depedency Injector
Figure 1.7: Our Hero Ninject Depedency Injector

First of all we need to install Ninject.MVC4 Nuget package in our web application, in other words in the Ioc.Web project.

MVC4 Nuget Package
Figure 1.8: Ninject.MVC4 Nuget Package

This package also installed the dependent page and our application has the following packages after its installation.

 

  1. Ninject
  2. Ninject.MVC4
  3. Ninject.Web.Common
  4. Ninject.Web.Common.WebHost

After its installation, the NinjectWebCommon class is created under the App_Start folder of the web application. The following code snippet is for this class.

  1. [assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Ioc.Web.App_Start.NinjectWebCommon), "Start")]  
  2. [assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(Ioc.Web.App_Start.NinjectWebCommon), "Stop")]  
  3.   
  4. namespace Ioc.Web.App_Start  
  5. {  
  6.     using System;  
  7.     using System.Web;  
  8.     using Ioc.Core.Data;  
  9.     using Ioc.Data;  
  10.     using Ioc.Service;  
  11.     using Microsoft.Web.Infrastructure.DynamicModuleHelper;  
  12.     using Ninject;  
  13.     using Ninject.Web.Common;  
  14.   
  15.     public static class NinjectWebCommon   
  16.     {  
  17.         private static readonly Bootstrapper bootstrapper = new Bootstrapper();  
  18.   
  19.         /// <summary>  
  20.         /// Starts the application  
  21.         /// </summary>  
  22.         public static void Start()   
  23.         {  
  24.             DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));  
  25.             DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));  
  26.             bootstrapper.Initialize(CreateKernel);  
  27.         }  
  28.           
  29.         /// <summary>  
  30.         /// Stops the application.  
  31.         /// </summary>  
  32.         public static void Stop()  
  33.         {  
  34.             bootstrapper.ShutDown();  
  35.         }  
  36.           
  37.         /// <summary>  
  38.         /// Creates the kernel that will manage your application.  
  39.         /// </summary>  
  40.         /// <returns>The created kernel.</returns>  
  41.         private static IKernel CreateKernel()  
  42.         {  
  43.             var kernel = new StandardKernel();  
  44.             try  
  45.             {  
  46.                 kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);  
  47.                 kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();  
  48.   
  49.                 RegisterServices(kernel);  
  50.                 return kernel;  
  51.             }  
  52.             catch  
  53.             {  
  54.                 kernel.Dispose();  
  55.                 throw;  
  56.             }  
  57.         }  
  58.   
  59.         /// <summary>  
  60.         /// Load your modules or register your services here!  
  61.         /// </summary>  
  62.         /// <param name="kernel">The kernel.</param>  
  63.         private static void RegisterServices(IKernel kernel)  
  64.         {  
  65.             kernel.Bind<IDbContext>().To<IocDbContext>().InRequestScope();  
  66.             kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();              
  67.             kernel.Bind<IUserService>().To<UserService>();  
  68.         }          
  69.     }  
  70. }   
In the RegisterServices() method of the preceding code, we bind the interface to the concrete classes. By this the concrete class object assigned to bind the interface instance.

CRUD Operations Model and Controller

Our user interface form is common for both User and UserProfile entities so we create a model depending on the model. We define UserModel (UserModel.cs) under the Models folder and the following code snippet for it.
  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace Ioc.Web.Models  
  5. {  
  6.     public class UserModel  
  7.     {  
  8.         public Int64 ID { getset; }  
  9.         [Display(Name ="First Name")]  
  10.         public string FirstName { getset; }  
  11.         [Display(Name="Last Name")]  
  12.         public string LastName { getset; }  
  13.         public string Address { getset; }  
  14.         [Display(Name="User Name")]  
  15.         public string UserName { getset; }  
  16.         public string Email { getset; }  
  17.         public string Password { getset; }  
  18.         [Display(Name ="Added Date")]  
  19.         public DateTime AddedDate { getset; }  
  20.     }  
  21. }   
We create a controller to do these CRUD operations. Create a UserController under the Controllers folder of the application. This controller has all the ActionResult methods for each user interface of a CRUD operation. We first create a IUserInterface instance then the controller's constructor initiates the service using dependency injection. The following is a code snippet for the UserController.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Mvc;  
  5. using Ioc.Service;  
  6. using Ioc.Web.Models;  
  7. using Ioc.Core.Data;  
  8.   
  9. namespace Ioc.Web.Controllers  
  10. {  
  11.     public class UserController : Controller  
  12.     {  
  13.   
  14.         private IUserService userService;  
  15.   
  16.         public UserController(IUserService userService)  
  17.         {  
  18.             this.userService = userService;  
  19.         }  
  20.   
  21.         [HttpGet]  
  22.         public ActionResult Index()  
  23.         {  
  24.             IEnumerable<UserModel> users = userService.GetUsers().Select(u => new UserModel  
  25.             {  
  26.                 FirstName = u.UserProfile.FirstName,  
  27.                 LastName = u.UserProfile.LastName,  
  28.                 Email = u.Email,  
  29.                 Address = u.UserProfile.Address,  
  30.                 ID = u.ID  
  31.             });  
  32.             return View(users);  
  33.         }  
  34.   
  35.         [HttpGet]  
  36.         public ActionResult CreateEditUser(int? id)  
  37.         {  
  38.             UserModel model = new UserModel();  
  39.             if (id.HasValue && id != 0)  
  40.             {  
  41.                 User userEntity = userService.GetUser(id.Value);  
  42.                 model.FirstName = userEntity.UserProfile.FirstName;  
  43.                 model.LastName = userEntity.UserProfile.LastName;  
  44.                 model.Address = userEntity.UserProfile.Address;  
  45.                 model.Email = userEntity.Email;  
  46.                 model.UserName = userEntity.UserName;  
  47.                 model.Password = userEntity.Password;  
  48.             }  
  49.             return View(model);  
  50.         }  
  51.   
  52.         [HttpPost]  
  53.         public ActionResult CreateEditUser(UserModel model)  
  54.         {  
  55.             if (model.ID == 0)  
  56.             {  
  57.                 User userEntity = new User  
  58.                 {  
  59.                     UserName = model.UserName,  
  60.                     Email = model.Email,  
  61.                     Password = model.Password,  
  62.                     AddedDate = DateTime.UtcNow,  
  63.                     ModifiedDate = DateTime.UtcNow,  
  64.                     IP = Request.UserHostAddress,  
  65.                     UserProfile = new UserProfile  
  66.                     {  
  67.                         FirstName = model.FirstName,  
  68.                         LastName = model.LastName,  
  69.                         Address = model.Address,  
  70.                         AddedDate = DateTime.UtcNow,  
  71.                         ModifiedDate = DateTime.UtcNow,  
  72.                         IP = Request.UserHostAddress  
  73.                     }  
  74.                 };  
  75.                 userService.InsertUser(userEntity);  
  76.                 if (userEntity.ID > 0)  
  77.                 {  
  78.                     return RedirectToAction("index");  
  79.                 }  
  80.             }  
  81.             else  
  82.             {  
  83.                 User userEntity = userService.GetUser(model.ID);  
  84.                 userEntity.UserName = model.UserName;  
  85.                 userEntity.Email = model.Email;  
  86.                 userEntity.Password = model.Password;  
  87.                 userEntity.ModifiedDate = DateTime.UtcNow;  
  88.                 userEntity.IP = Request.UserHostAddress;  
  89.                 userEntity.UserProfile.FirstName = model.FirstName;  
  90.                 userEntity.UserProfile.LastName = model.LastName;  
  91.                 userEntity.UserProfile.Address = model.Address;  
  92.                 userEntity.UserProfile.ModifiedDate = DateTime.UtcNow;  
  93.                 userEntity.UserProfile.IP = Request.UserHostAddress;  
  94.                 userService.UpdateUser(userEntity);  
  95.                 if (userEntity.ID > 0)  
  96.                 {  
  97.                     return RedirectToAction("index");  
  98.                 }  
  99.                  
  100.             }  
  101.             return View(model);  
  102.         }  
  103.   
  104.         public ActionResult DetailUser(int? id)  
  105.         {  
  106.             UserModel model = new UserModel();  
  107.             if (id.HasValue && id != 0)  
  108.             {  
  109.                 User userEntity = userService.GetUser(id.Value);  
  110.                // model.ID = userEntity.ID;  
  111.                 model.FirstName = userEntity.UserProfile.FirstName;  
  112.                 model.LastName = userEntity.UserProfile.LastName;  
  113.                 model.Address = userEntity.UserProfile.Address;  
  114.                 model.Email = userEntity.Email;  
  115.                 model.AddedDate = userEntity.AddedDate;  
  116.                 model.UserName = userEntity.UserName;  
  117.             }  
  118.             return View(model);  
  119.         }  
  120.   
  121.         public ActionResult DeleteUser(int id)  
  122.         {  
  123.             UserModel model = new UserModel();  
  124.             if (id != 0)  
  125.             {  
  126.                 User userEntity = userService.GetUser(id);                  
  127.                 model.FirstName = userEntity.UserProfile.FirstName;  
  128.                 model.LastName = userEntity.UserProfile.LastName;  
  129.                 model.Address = userEntity.UserProfile.Address;  
  130.                 model.Email = userEntity.Email;  
  131.                 model.AddedDate = userEntity.AddedDate;  
  132.                 model.UserName = userEntity.UserName;  
  133.             }  
  134.             return View(model);  
  135.         }  
  136.   
  137.          
  138.         [HttpPost]  
  139.         public ActionResult DeleteUser(int id, FormCollection collection)  
  140.         {  
  141.             try  
  142.             {  
  143.                 if ( id != 0)  
  144.                 {  
  145.                     User userEntity = userService.GetUser(id);      
  146.                     userService.DeleteUser(userEntity);  
  147.                     return RedirectToAction("Index");  
  148.                 }  
  149.                 return View();  
  150.             }  
  151.             catch  
  152.             {  
  153.                 return View();  
  154.             }  
  155.         }  
  156.     }  
  157. }  
Before starting the UI design we have a look at its constructor, we are using IUserService as the parameter of the constructor and here we are injecting the class object that binds from the IUserService interface in the Dependency Injection container.

Dependency Inject
Figure 1.9: Dependency Inject

We have now developed the UserController to handle the CRUD operations request for both the User and UserProfile entities. Thereafter we develop the user interface for the CRUD operations. We develop it for the views for adding and editing a user, a user listing, user delete and user details. Let's see each one by one.

Create / Edit User View

We create a common view for creating and editing a user such as CreateEditUser.cshtml under the User folder of the views. Now define a create/edit user view and the following is a code snippet for CreateEditUser.cshtml.
  1. @model Ioc.Web.Models.UserModel  
  2. @{  
  3.     ViewBag.Title = "Create Edit User";  
  4. }  
  5. <div class="book-example panel panel-primary">  
  6.     <div class="panel-heading panel-head">Add / Edit User</div>  
  7.     <div class="panel-body">  
  8.         @using (Html.BeginForm())  
  9.         {         
  10.             <div class="form-horizontal">  
  11.                 <div class="form-group">  
  12.                     @Html.LabelFor(model => model.FirstName, new { @class = "col-lg-2 control-label" })  
  13.                     <div class="col-lg-9">  
  14.                         @Html.TextBoxFor(model => model.FirstName, new { @class = "form-control" })  
  15.                     </div>  
  16.                 </div>  
  17.                 <div class="form-group">  
  18.                     @Html.LabelFor(model => model.LastName, new { @class = "col-lg-2 control-label" })  
  19.                     <div class="col-lg-9">  
  20.                         @Html.TextBoxFor(model => model.LastName, new { @class = "form-control" })  
  21.                     </div>  
  22.                 </div>  
  23.                 <div class="form-group">  
  24.                     @Html.LabelFor(model => model.Email, new { @class = "col-lg-2 control-label" })  
  25.                     <div class="col-lg-9">  
  26.                         @Html.TextBoxFor(model => model.Email, new { @class = "form-control" })  
  27.                     </div>  
  28.                 </div>  
  29.                 <div class="form-group">  
  30.                     @Html.LabelFor(model => model.UserName, new { @class = "col-lg-2 control-label" })  
  31.                     <div class="col-lg-9">  
  32.                         @Html.TextBoxFor(model => model.UserName, new { @class = "form-control" })  
  33.                     </div>  
  34.                 </div>  
  35.                  <div class="form-group">  
  36.                     @Html.LabelFor(model => model.Password, new { @class = "col-lg-2 control-label" })  
  37.                     <div class="col-lg-9">  
  38.                         @Html.PasswordFor(model => model.Password,new { @class = "form-control" })  
  39.                     </div>  
  40.                 </div>  
  41.                  <div class="form-group">  
  42.                     @Html.LabelFor(model => model.Address, new { @class = "col-lg-2 control-label" })  
  43.                     <div class="col-lg-9">  
  44.                         @Html.TextBoxFor(model => model.Address, new { @class = "form-control" })  
  45.                     </div>  
  46.                 </div>  
  47.                 <div class="form-group">  
  48.                     <div class="col-lg-9"></div>  
  49.                     <div class="col-lg-3">  
  50.                         @Html.ActionLink("Back to List""Index"nullnew { @class = "btn btn-default" })  
  51.                         <button class="btn btn-success" id="btnSubmit" type="submit">  
  52.                             Submit  
  53.                         </button>  
  54.                     </div>  
  55.                 </div>  
  56.             </div>         
  57.         }  
  58.     </div>  
  59. </div>  
Now run the application and call the CreateEditUser() action method with a HttpGet request, then we get the UI as in Figure 1.10 to add a new user to the application.

Add new user UI
Figure 1.10: Add new user UI

User List View

This is the first view when the application is accessed or the entry point of the application is executed. It shows the user listing as in Figure 1.11. We display user data in tabular format and on this view, we create links to add a new user, edit a user, delete a user and the details of a user. This view is an index view and the following is a code snippet for index.cshtml under the User folder of the View.
  1. @model IEnumerable<Ioc.Web.Models.UserModel>  
  2.   
  3. <div class="book-example panel panel-primary">  
  4.     <div class="panel-heading panel-head">Users Listing</div>  
  5.     <div class="panel-body">  
  6.         <a id="createEditBookModal" href="@Url.Action("CreateEditUser")" class="btn btn-success">  
  7.             <span class="glyphicon glyphicon-plus"></span> User  
  8.         </a>  
  9.   
  10.         <table class="table" style="margin: 4px">  
  11.             <tr>  
  12.                 <th>  
  13.                     @Html.DisplayName("Name")  
  14.                 </th>  
  15.                 <th>  
  16.                     @Html.DisplayNameFor(model => model.Email)  
  17.                 </th>  
  18.                 <th>  
  19.                     @Html.DisplayNameFor(model => model.Address)  
  20.                 </th>  
  21.                 <th>Action  
  22.                 </th>  
  23.                 <th></th>  
  24.             </tr>  
  25.             @foreach (var item in Model)  
  26.             {  
  27.                 <tr>  
  28.                     <td>  
  29.                         @Html.DisplayFor(modelItem => item.FirstName) @Html.DisplayFor(modelItem=>item.LastName)  
  30.                     </td>  
  31.                     <td>  
  32.                         @Html.DisplayFor(modelItem => item.Email)  
  33.                     </td>  
  34.                     <td>  
  35.                         @Html.DisplayFor(modelItem => item.Address)  
  36.                     </td>  
  37.                     <td>  
  38.                         @Html.ActionLink("Edit""CreateEditUser"new { id = item.ID }, new { @class = "btn btn-success" })  
  39.                         @Html.ActionLink("Details""DetailUser"new { id = item.ID }, new { @class = "btn btn-primary" })  
  40.                         @Html.ActionLink("Delete""DeleteUser"new { id = item.ID }, new { @class = "btn btn-danger" })  
  41.                     </td>  
  42.                 </tr>  
  43.             }  
  44.   
  45.         </table>  
  46.     </div>  
  47. </div>  
When we run the application and call the index() action with an HttpGet request, then we get all the users listed in the UI as in Figure 1.11. This UI has options for CRUD operations.

User Listing UI
Figure 1.11: User Listing UI

As in the figure above, the user queue has an option for Edit. When we click on the Edit button then the CreateEditUser() action method is called with an HttpGet request and the UI is shown as in Figure 1.12.

Edit a User UI
Figure 1.12: Edit a User UI

Now, we change the input field data and click on the submit button, then the CreateEditUser() action method is called with a HttpPost request and that user data is successfully updated in the database.

User Detail View

We create a view that shows the specific user details when the details button is clicked in the user listing data. We call the DetailUser() action method with a HttpGet request that shows a “Details” view such as in Figure 1.13 so we create a view DetailUser and the following is the code snippet for DetailUser.cshtml.
  1. @model Ioc.Web.Models.UserModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "User Detail";  
  5. }  
  6.   
  7. <div class="book-example panel panel-primary">  
  8.     <div class="panel-heading panel-head">User Detail</div>  
  9.     <div class="panel-body">  
  10.         <div class="form-horizontal">  
  11.             <div class="form-group">  
  12.                 @Html.LabelFor(model => model.FirstName, new { @class = "col-lg-2 control-label" })  
  13.                 <div class="col-lg-9">  
  14.                     @Html.DisplayFor(model => model.FirstName, new { @class = "form-control" })  
  15.                 </div>  
  16.             </div>  
  17.   
  18.             <div class="form-group">  
  19.                 @Html.LabelFor(model => model.LastName, new { @class = "col-lg-2 control-label" })  
  20.                 <div class="col-lg-9">  
  21.                     @Html.DisplayFor(model => model.LastName, new { @class = "form-control" })  
  22.                 </div>  
  23.             </div>  
  24.   
  25.             <div class="form-group">  
  26.                 @Html.LabelFor(model => model.UserName, new { @class = "col-lg-2 control-label" })  
  27.                 <div class="col-lg-9">  
  28.                     @Html.DisplayFor(model => model.UserName, new { @class = "form-control" })  
  29.                 </div>  
  30.             </div>  
  31.   
  32.             <div class="form-group">  
  33.                 @Html.LabelFor(model => model.Email, new { @class = "col-lg-2 control-label" })  
  34.                 <div class="col-lg-9">  
  35.                     @Html.DisplayFor(model => model.Email, new { @class = "form-control" })  
  36.                 </div>  
  37.             </div>  
  38.   
  39.             <div class="form-group">  
  40.                 @Html.LabelFor(model => model.AddedDate, new { @class = "col-lg-2 control-label" })  
  41.                 <div class="col-lg-9">  
  42.                     @Html.DisplayFor(model => model.AddedDate, new { @class = "form-control" })  
  43.                 </div>  
  44.             </div>  
  45.   
  46.             <div class="form-group">  
  47.                 @Html.LabelFor(model => model.Address, new { @class = "col-lg-2 control-label" })  
  48.                 <div class="col-lg-9">  
  49.                     @Html.DisplayFor(model => model.Address, new { @class = "form-control" })  
  50.                 </div>  
  51.             </div>             
  52.   
  53.             @using (Html.BeginForm())  
  54.             {  
  55.                 <div class="form-group">  
  56.                     <div class="col-lg-2"></div>  
  57.                     <div class="col-lg-9">  
  58.                         @Html.ActionLink("Edit""CreateEditUser"new { id = ViewContext.RouteData.Values["id"] }, new { @class = "btn btn-primary" })  
  59.                         @Html.ActionLink("Back to List""Index"nullnew { @class = "btn btn-success" })  
  60.                     </div>  
  61.                 </div>  
  62.             }  
  63.         </div>  
  64.     </div>  
  65. </div>  
User Detail UI
Figure 1.13: User Detail UI

Delete User

Delete a user is the last operation of this article. To delete a user, we follow the process of clicking on the Delete button that exists in the User listing data. The user detail view then prompts to ask “You are sure you want to delete this?” after clicking on the Delete button that exists in the Delete view such as in Figure 1.14. When we click the Delete button of the user list, then it makes an HttpGet request that calls the DeleteUser() action method that shows a delete view, then clicks on the Delete button of the view, then an HttpPost request makes that call to the ConfirmDeleteUser() action methods that delete that user. The following is a code snippet for DeleteUser.cshtml.
  1. @model Ioc.Web.Models.UserModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "Delete User";  
  5. }  
  6.   
  7. <div class="book-example panel panel-primary">  
  8.     <div class="panel-heading panel-head">Delete User</div>  
  9.     <div class="panel-body">  
  10.         <h3>Are you sure you want to delete this?</h3>  
  11.         <h1>@ViewBag.ErrorMessage</h1>  
  12.         <div class="form-horizontal">  
  13.             <div class="form-group">  
  14.                 @Html.LabelFor(model => model.FirstName, new { @class = "col-lg-2 control-label" })  
  15.                 <div class="col-lg-9">  
  16.                     @Html.DisplayFor(model => model.FirstName, new { @class = "form-control" })  
  17.                 </div>  
  18.             </div>  
  19.   
  20.             <div class="form-group">  
  21.                 @Html.LabelFor(model => model.LastName, new { @class = "col-lg-2 control-label" })  
  22.                 <div class="col-lg-9">  
  23.                     @Html.DisplayFor(model => model.LastName, new { @class = "form-control" })  
  24.                 </div>  
  25.             </div>  
  26.   
  27.             <div class="form-group">  
  28.                 @Html.LabelFor(model => model.UserName, new { @class = "col-lg-2 control-label" })  
  29.                 <div class="col-lg-9">  
  30.                     @Html.DisplayFor(model => model.UserName, new { @class = "form-control" })  
  31.                 </div>  
  32.             </div>  
  33.   
  34.             <div class="form-group">  
  35.                 @Html.LabelFor(model => model.Email, new { @class = "col-lg-2 control-label" })  
  36.                 <div class="col-lg-9">  
  37.                     @Html.DisplayFor(model => model.Address, new { @class = "form-control" })  
  38.                 </div>  
  39.             </div>  
  40.   
  41.             <div class="form-group">  
  42.                 @Html.LabelFor(model => model.Address, new { @class = "col-lg-2 control-label" })  
  43.                 <div class="col-lg-9">  
  44.                     @Html.DisplayFor(model => model.Address, new { @class = "form-control" })  
  45.                 </div>  
  46.             </div>            
  47.   
  48.             @using (Html.BeginForm())  
  49.             {  
  50.                 <div class="form-group">  
  51.                     <div class="col-lg-2"></div>  
  52.                     <div class="col-lg-9">  
  53.                         <input type="submit" value="Delete" class="btn btn-danger" />  
  54.                         @Html.ActionLink("Back to List""Index"nullnew { @class = "btn btn-success" })  
  55.                     </div>  
  56.                 </div>  
  57.             }  
  58.         </div>  
  59.     </div>  
  60. </div>  
Delete a User UI
Figure1.14: Delete a User UI

Conclusion

This article introduced the Inversion of Control using Dependency Injection. I used Bootstrap CSS and JavaScript for the user interface design in this application. What do you think about this article? Please provide your feedback.

Download 

You can download complete solution source code using below URLs.
https://gallery.technet.microsoft.com/CRUD-Operations-Using-0aa46470