Dependency Injection And Repository Pattern in .Net Core MVC With Entity Framework Core

Implementing Repository + Dependency Injection in .Net core MVC with Entity framework core

 
In this blog I will create an application using .net Core MVC and Entity framework core, implementing Repository Pattern and Dependency Injection.

I will make the application loosely coupled as much as possible. The data access layer and UI will be completely independent of each other.
 
Prerequisite
 
Prior knowledge of MVC and Entity framework
 
Let’s begin.
 

Project Creation

 
I am using the Visual Studio 2019 community edition.

Open your IDE and create .net core MVC project
 
.Net Core MVC With Entity Framework Core Using Dependency Injection And Repository
 
Select Asp.Net Core Web Application and press next
 
.Net Core MVC With Entity Framework Core Using Dependency Injection And Repository
 
Name your solution and create
 
.Net Core MVC With Entity Framework Core Using Dependency Injection And Repository
 
Project is created.
 
The solution will have Controller, Model, View folder and one new wwwroot folder and a few more files named appsetting.json, Startup.cs, Program.cs.
 
Let’s understand what these files are.
 
Appsetting.json file is your web.config file.

Program.cs file is the same as in your console application and is called once for the entire application life cycle.

Startup.cs is used for configuring your .net core application.
 
Let us create a small module of adding product in an eCommerce website.
 

Model

 
First create a Product model in, for that we will create a new .net core class library project in the same solution
  1. namespace ECommerce.Entity  
  2. {  
  3.     [Table("Product")]  
  4.     public class Product  
  5.     {  
  6.         [Key]  
  7.         public string ProductId { getset;  }  
  8.         [Required]  
  9.         [MaxLength(50)]  
  10.         public string ProductName { getset; }  
  11.         [MaxLength(300)]  
  12.         public string ProductDescription { getset; }  
  13.         [Required]  
  14.         [DisplayName("Category")]  
  15.         public string CategoryId { getset; }  
  16.         [Required]  
  17.         public double QuantityPerUnit { getset; }  
  18.         [Required]  
  19.         public double UnitPrice { getset; }  
  20.         [Required]  
  21.         public double MSRP { getset; }  
  22.         public double AvailableSize { getset; }  
  23.         public string AvailableColor { getset; }  
  24.         public double Discount { getset; }  
  25.         [Required]  
  26.         public double UnitWeight { getset; }  
  27.         [Required]  
  28.         public double UnitsInStock { getset; }  
  29.         public double UnitsOnOrder { getset; }  
  30.         public double ProductAvailability { getset; }  
  31.         public string Picture { getset; }  
  32.         public string Note { getset; }  
  33.     }  
  34. }  
This model will be used to save data and bind view and controller.
 

Entity framework core Context

 
The next step is to create Entity framework core context. For that we create a new .net core class library project and install a nugget package in it.
 
.Net Core MVC With Entity Framework Core Using Dependency Injection And Repository
 
Create a ECommerceContext class
  1. namespace ECommerce.DAL  
  2. {  
  3.     public class ECommerceContext : DbContext  
  4.     {  
  5.         public ECommerceContext(DbContextOptions<ECommerceContext> options) : base(options)  
  6.         {  
  7.               
  8.         }  
  9.   
  10.         public DbSet<Category> Categories { getset; }  
  11.         public DbSet<Product> Products { getset; }  
  12.     }  
  13. }  

Repository

 
Now let’s create a new .net core class library project named Ecommerce.IRepositories.
 
And create an interface in the project. This project will only contain Interfaces.
  1. namespace ECommerce.IRepos  
  2. {  
  3.     public interface IProductRepository  
  4.     {  
  5.         IList<Product> GetProducts();  
  6.         Product GetProduct(string productId);  
  7.         void Add(Product product);  
  8.         Product Update(Product product);  
  9.         void Delete(Product product);  
  10.     }  
  11. }  
Interfaces play a key role in making the application loosely coupled and more injectable.
 
To implement this interface we’ll create another .net core class library project for repository.
 
Name Ecommerce.Repositories and create a class.
  1. namespace ECommerce.Repos  
  2. {  
  3.     public class ProductRepository : IProductRepository  
  4.     {  
  5.         private readonly ECommerceContext productContext;  
  6.         public ProductRepository(ECommerceContext context)  
  7.         {  
  8.             productContext = context;  
  9.         }  
  10.   
  11.         public void Add(Product product)  
  12.         {  
  13.             product.ProductId = Guid.NewGuid().ToString();  
  14.             productContext.Add(product);  
  15.             productContext.SaveChanges();  
  16.         }  
  17.   
  18.         public void Delete(Product product)  
  19.         {  
  20.             productContext.Products.Remove(product);  
  21.             productContext.SaveChanges();  
  22.         }  
  23.   
  24.         public IList<Product> GetProducts()  
  25.         {  
  26.             return productContext.Products.ToList();  
  27.         }  
  28.   
  29.         public Product GetProduct(string productId)  
  30.         {  
  31.             return productContext.Products.FirstOrDefault(x=> x.ProductId == productId);  
  32.         }  
  33.   
  34.         public Product Update(Product productChanges)  
  35.         {  
  36.             var product = productContext.Products.Attach(productChanges);  
  37.             product.State = Microsoft.EntityFrameworkCore.EntityState.Modified;  
  38.             productContext.SaveChanges();  
  39.             return productChanges;  
  40.         }  
  41.     }  
  42. }  
Now, we have created our context, our model and our repository.
 

Application

 
It’s time to create a controller named ProductController.cs and inject all the dependencies in it. To inject the dependencies we need to configure startup.cs file.
 
Add the following code in ConfigureService method.
  1. services.AddScoped<IProductRepository, ProductRepository>();  
  2. services.AddDbContextPool<ECommerceContext>(x => x.UseSqlServer(ConnectionString, b => b.MigrationsAssembly("ECommerce")));  
The controller will look like the below code.
  1. IProductRepository productRepo = null;  
  2. public ProductController(IProductRepository prodRepo)  
  3. {  
  4.      productRepo = prodRepo;  
  5. }  
As you can see we are using parameterized constructor of controller to inject the dependency.
 
In .net core there is  built in support for dependency injection.
  1. services.AddScoped<IProductRepository, ProductRepository>();  
The above line is used to inject any dependency in controller.
 
The below method is used to save Product detail in database.
  1. public ActionResult SaveProduct(Product product)  
  2. {  
  3.       if (ModelState.IsValid)  
  4.       {  
  5.            if (string.IsNullOrEmpty(product.ProductId))  
  6.            {  
  7.                 productRepo.Add(product);  
  8.            }  
  9.            else {  
  10.                 product = productRepo.Update(product);  
  11.            }  
  12.       }  
  13.       return View("Create");  
  14. }   
View to controller binding is the same as it was in the MVC application and I understand you guys are better at that so I'm not going through it.
 
Notes
If you look at the Repository class, I have injected context class in its constructor.
 

Summary

 
This is how you create a .net core MVC application with repository and dependency injection which is loosely coupled and easily configurable.
I am open to all kinds of discussion. Feel free to comment and suggest anything.
 
Thank you.