Tuesday, 26 May 2020

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. 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 visual studio 2019 community edition.
Open your IDE and create .net core MVC project



Select Asp.Net Core Web Application and press next


Name your solution and create


Project is created

The solution will have Controller, Model, View folder and one new wwwroot folder and 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 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 Ecommerce website

Model

First create a Product model in, for that we will create a new .net core class library project in same solution

namespace ECommerce.Entity

{

    [Table("Product")]

    public class Product

    {

        [Key]

        public string ProductId { get; set;  }

        [Required]

        [MaxLength(50)]

        public string ProductName { get; set; }

        [MaxLength(300)]

        public string ProductDescription { get; set; }

        [Required]

        [DisplayName("Category")]

        public string CategoryId { get; set; }

        [Required]

        public double QuantityPerUnit { get; set; }

        [Required]

        public double UnitPrice { get; set; }

        [Required]

        public double MSRP { get; set; }

        public double AvailableSize { get; set; }

        public string AvailableColor { get; set; }

        public double Discount { get; set; }

        [Required]

        public double UnitWeight { get; set; }

        [Required]

        public double UnitsInStock { get; set; }

        public double UnitsOnOrder { get; set; }

        public double ProductAvailability { get; set; }

        public string Picture { get; set; }

        public string Note { get; set; }

    }

}

 

This model will be used to save data and bind view and controller.

 

Entity framework core Context

 

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.

Create a ECommerceContext class

public class ECommerceContext : DbContext

    {

        public ECommerceContext(DbContextOptions<ECommerceContext> options) : base(options)

        {

           

        }

 

        public DbSet<Product> Products { get; set; }

    } 

 

 

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

 

public interface IProductRepository

    {

        IList<Product> GetProducts();

        Product GetProduct(string productId);

        void Add(Product product);

        Product Update(Product product);

        void Delete(Product product);

    }

Interfaces plays key roles in making application loosely coupled and more injectable more

 

To implement this interface we’ll create another .net core class library project for repository

Name Ecommerce.Repositories and create a class

 

public class ProductRepository : IProductRepository

    {

        private readonly ECommerceContext productContext;

        public ProductRepository(ECommerceContext context)

        {

            productContext = context;

        }

 

        public void Add(Product product)

        {

            product.ProductId = Guid.NewGuid().ToString();

            productContext.Add(product);

            productContext.SaveChanges();

        }

 

        public void Delete(Product product)

        {

            productContext.Products.Remove(product);

            productContext.SaveChanges();

        }

 

        public IList<Product> GetProducts()

        {

            return productContext.Products.ToList();

        }

 

        public Product GetProduct(string productId)

        {

            return productContext.Products.FirstOrDefault(x=> x.ProductId == productId);

        }

 

        public Product Update(Product productChanges)

        {

            var product = productContext.Products.Attach(productChanges);

            product.State = Microsoft.EntityFrameworkCore.EntityState.Modified;

            productContext.SaveChanges();

            return productChanges;

        }

    }

 

Now, we have created our context, our model and our repository.

 

Application

 

It’s time to create controller named ProductController.cs and inject all the dependency in it. To inject the dependencies we need to configure startup.cs file

 

Add following code in ConfigureService method

 

services.AddScoped<IProductRepository, ProductRepository>();

services.AddDbContextPool<ECommerceContext>(x => x.UseSqlServer(ConnectionString, b => b.MigrationsAssembly("ECommerce")));

controller will look like below code

IProductRepository productRepo = null;

public ProductController(IProductRepository prodRepo)

{

productRepo = prodRepo;

}

As you can see we are using parameterized constructor of controller to inject the dependency.

.net core there is a build in support for dependency injection

            services.AddScoped<IProductRepository, ProductRepository>();

Above line is used to inject any dependency in controller

Below method is used to save Product detail in database

public ActionResult SaveProduct(Product product)

        {

            int res = 3;

            if (ModelState.IsValid)

            {

                if (string.IsNullOrEmpty(product.ProductId))

                {

                    productRepo.Add(product);

                }

                else {

                    product = productRepo.Update(product);

                }

                res = 1;

            }

            else {

            }

            return View("Create");

        }

View to controller binding is same as it was in MVC application and I understand you guys are better at that so not going through with 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 kind of discussion. Feel free to comment and suggest anything

Thank you.

 


Send All Azure App Insights Or Logs Data To Tool Like Datadog

  Introduction Microsoft Azure provides a variety of insights and monitoring logs that you can monitor to check the state of a resource and ...