Repository Pattern with Dependency Injection in Asp.net core with Code First Approach | Dependency Injection in ASP.NET Core
Hello & As-salam u alikum ! , In this article we are going to learn the following concepts in a single Project.
https://dotnetcorecommunity.blogspot.com/p/aspnet-core-tutorials-paracticals.html
Step# 1:
Step# 4:
- Dependency Injection in Asp.net Core
- Repository Pattern in Asp.net Core C#
- Code First Approach in Asp.net Core
https://dotnetcorecommunity.blogspot.com/p/aspnet-core-tutorials-paracticals.html
Step# 1:
Read all the previous articles and implement for getting some basic skills and confidence to work on asp.net core . Well if you are not new to .net technology or you may had worked on Asp.net mvc previous .net framework versions, than its not going to be difficult for you to understand these concepts.
Step# 2:
Create An Mvc Project in asp.net core as I explained in my previous articles.
Than you will have a project folder Structure like the below Image shown.
Step# 3:
In the very next step just focus on the model folder , Here we are going to make a class or define entity Class named as "Student" and add some get set properties to that class as shown below.
namespace CODEFIRSTCORE.Models
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Email { get; set; }
}
}
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Email { get; set; }
}
}
Step# 4:
Now we are going to Define our second Class which will make the bridge or connection b/w data source (SQL-SERVER) & our application. In my project, I am going to name this class as "DependencyInjectionContext" now code in that class as shown below.
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace demoinjection.Models
{
public partial class DependencyInjectionContext : DbContext
{
public DependencyInjectionContext()
{
}
public DependencyInjectionContext(DbContextOptions<DependencyInjectionContext> options)
: base(options)
{
}
public virtual DbSet<TblStudent> TblStudent { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
}
}
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace demoinjection.Models
{
public partial class DependencyInjectionContext : DbContext
{
public DependencyInjectionContext()
{
}
public DependencyInjectionContext(DbContextOptions<DependencyInjectionContext> options)
: base(options)
{
}
public virtual DbSet<TblStudent> TblStudent { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
}
}
Step# 5:
Add an interface named as "IStudentRepository" and add the method signatures to the interface as shown below.
In the above code, I have created methods for CRUD operation.
Step# 6:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CODEFIRSTCORE.Models
{
public interface IStudentRepository
{
Student GetStudent(int Id);
IEnumerable<Student> GetAll();
Student Add(Student Student);
Student Update(Student Student);
Student Delete(int Id);
}
}
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CODEFIRSTCORE.Models
{
public interface IStudentRepository
{
Student GetStudent(int Id);
IEnumerable<Student> GetAll();
Student Add(Student Student);
Student Update(Student Student);
Student Delete(int Id);
}
}
In the above code, I have created methods for CRUD operation.
Step# 6:
Add a class named as "StudentRepository" which will implement the Interface "IStudentRepository" , In this repository class we will implement all the methods that we had defined in our interface.
In the above highlighted code, you may noticed that I have not created an objection DependencyInjectionContextclass, I just passed the reference of that class in constructor to initialize the objection of DependencyInjectionContext class, this is called Constructor Injection (a common type of dependency Injection).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace demoinjection.Models
{
public class SqlRepository : IStudentRepository
{
private readonly DependencyInjectionContext db;
public SqlRepository(DependencyInjectionContext db)
{
this.db = db;
}
public TblStudent Add(TblStudent Student)
{
db.TblStudent.Add(Student);
db.SaveChanges();
return Student;
}
public TblStudent Delete(int Id)
{
TblStudent Student = db.TblStudent.Find(Id);
if (Student != null)
{
db.TblStudent.Remove(Student);
db.SaveChanges();
}
return Student;
}
public IEnumerable<TblStudent> GetAll()
{
return db.TblStudent;
}
public TblStudent GetStudent(int Id)
{
return db.TblStudent.Where(x => x.Id == Id).SingleOrDefault();
}
public TblStudent Update(TblStudent Student)
{
throw new NotImplementedException();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace demoinjection.Models
{
public class SqlRepository : IStudentRepository
{
private readonly DependencyInjectionContext db;
public SqlRepository(DependencyInjectionContext db)
{
this.db = db;
}
public TblStudent Add(TblStudent Student)
{
db.TblStudent.Add(Student);
db.SaveChanges();
return Student;
}
public TblStudent Delete(int Id)
{
TblStudent Student = db.TblStudent.Find(Id);
if (Student != null)
{
db.TblStudent.Remove(Student);
db.SaveChanges();
}
return Student;
}
public IEnumerable<TblStudent> GetAll()
{
return db.TblStudent;
}
public TblStudent GetStudent(int Id)
{
return db.TblStudent.Where(x => x.Id == Id).SingleOrDefault();
}
public TblStudent Update(TblStudent Student)
{
throw new NotImplementedException();
}
}
}
In the above highlighted code, you may noticed that I have not created an objection DependencyInjectionContextclass, I just passed the reference of that class in constructor to initialize the objection of DependencyInjectionContext class, this is called Constructor Injection (a common type of dependency Injection).
Step# 7:
Next step is to configure the middle-ware related to dependency and Entity framework. Just open the Startup.cs File and add the following highlighted code in the ConfigureServices method.
while adding these lines of code, you will get error at useSqlServer method. just add the following nameSpaces on the top.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CODEFIRSTCORE.Models; // (Project model reference ,this may change in your project according to your project name)
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Now I need to add the same key as connection string in Appsetting.json file as shown.
Connection string Format:
"Server=.;Database=StudentDb;user id=salman;password=ww12345"
server name is "." which means current PC Server, you may change the database name, and my sql server is running on sql server Authentications, so I m providing the credentials. if you are not able or sure to make connection string ,you can get it from solution Explorer too. Well, in case of problem comment the problem, I ll reply you as soon as possible.
Step# 9:
Now the next step is migration , open the package manager console.
and type following command and press Enter.
now the next command is :
Step# 10:
Now, Open the Sql server Management Studio and you will find your created database in the list. Add some records to Student Table to show on view.
insert into Student values('Wajahat','Gulshan block 5 Karachi','wajaht@gmail.com')
insert into Student values('talha','power house north karachi','talha@gmail.com')
Step# 11:
Now, go to the Visual Studio back & open the controller , In home controller Right click on view add view using scaffolding.
After adding the view ,you will have a default created table html with respect to Student Entity.
Now the main step is to inject interface "IStudentRepository" in the home controller constructor.
as you noticed that I have inject the interface repository instead of adding the database connection class or student repository class , If i were added the instance of dbContext or studentrepository class ,my code would become tightly coupled ,when ever I had to make changes I need to change the every instance of dbContext or studentrepository in every Controller where ever I used while coding. you may noticed that I have called a function in Index action method to retrieve all the records from Student table.
Step# 12:
Run the code, you will get an the following view .
Conclusion :
that's all for this blog, we have successfully fetch data from sql server table, we have created our database using code first approach and we have used repository pattern and a design principle Dependency Injection , In my next article I ll show you the benefit of loosely coupled code as I have used Dependency injection, so I ll just have to change few lines to change the data source and my app won't get crashed by these changes. Thank you for reading . Have a good day.
while adding these lines of code, you will get error at useSqlServer method. just add the following nameSpaces on the top.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CODEFIRSTCORE.Models; // (Project model reference ,this may change in your project according to your project name)
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Step# 8:
Now set the connectionstring in Appsetting.json file as you may noticed I have used a key named as StudentDBConnection in connectionstring method , I have circled it with red pen, notice that please.
Connection string Format:
"Server=.;Database=StudentDb;user id=salman;password=ww12345"
server name is "." which means current PC Server, you may change the database name, and my sql server is running on sql server Authentications, so I m providing the credentials. if you are not able or sure to make connection string ,you can get it from solution Explorer too. Well, in case of problem comment the problem, I ll reply you as soon as possible.
Step# 9:
Now the next step is migration , open the package manager console.
and type following command and press Enter.
now the next command is :
Step# 10:
Now, Open the Sql server Management Studio and you will find your created database in the list. Add some records to Student Table to show on view.
Queries to Insert Records:
insert into Student values('salman','sector 3 north karachi','theideassolution@gmail.com')insert into Student values('Wajahat','Gulshan block 5 Karachi','wajaht@gmail.com')
insert into Student values('talha','power house north karachi','talha@gmail.com')
Now, go to the Visual Studio back & open the controller , In home controller Right click on view add view using scaffolding.
After adding the view ,you will have a default created table html with respect to Student Entity.
Now the main step is to inject interface "IStudentRepository" in the home controller constructor.
as you noticed that I have inject the interface repository instead of adding the database connection class or student repository class , If i were added the instance of dbContext or studentrepository class ,my code would become tightly coupled ,when ever I had to make changes I need to change the every instance of dbContext or studentrepository in every Controller where ever I used while coding. you may noticed that I have called a function in Index action method to retrieve all the records from Student table.
Step# 12:
Run the code, you will get an the following view .
Conclusion :
that's all for this blog, we have successfully fetch data from sql server table, we have created our database using code first approach and we have used repository pattern and a design principle Dependency Injection , In my next article I ll show you the benefit of loosely coupled code as I have used Dependency injection, so I ll just have to change few lines to change the data source and my app won't get crashed by these changes. Thank you for reading . Have a good day.
0 Comments:
Post a Comment
Do not Add Spam links in the Comment Box
Subscribe to Post Comments [Atom]
<< Home