Getting Started With Unity IoC Container Dependency Injection In .NET Core Using Entity Framework Core ORM And SQL Server
Hello Fellow Programmers!
Visual Basic Version: Using Unity IoC Container Dependency Injection, Dapper ORM and SQL Server In Visual Basic .NET Core Or .NET 5 Application
2. Add three new folders Models, Repository and UnitOfWork. These folders contain the models and DAL classes used in this project. 3. Add the following NuGet packages: Microsoft.EntityFrameworkCore,Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Tools, System.Configuration.ConfigurationManager and Unity IoC container. 4. Reverse Engineer the ContosoRetailsDW by running the Scaffold-DbContext in Package Manager Console as we will use the Database First Approach. Replace the Server attribute with your default server.
3. Add an IEmployeeRepository interface that inherits the IRepository interface with the Employee type.
4. Then create an EmployeeRepository class that inherits both the generic repository and base repository.
5. After creating our repository classes and interface, well then proceed with the Unit Of Work pattern. First is to create an IUnitOfWork interface with an EmployeeRepository property that is of type IEmployeeRepository.
6. Next is to generate a class that inherits the IUnitOfWork interface. This class implements the EmployeeRepository property with a getter and private setter accessors. The constructor of this class accepts an IEmployeeRepository parameter which will then be resolved by the Unity IoC container.
Visual Basic Version: Using Unity IoC Container Dependency Injection, Dapper ORM and SQL Server In Visual Basic .NET Core Or .NET 5 Application
In this article, I'll demonstrate on how to incorporate the Unity IoC Container into a .NET Core Console Application using Entity Framework Core ORM and SQL Server.This will apply the constructor injection methodology of dependency injection where in dependencies are provided through a constructor. I've used this IoC Container several years ago and have not done any coding after that. So it's time to revisit this terrific tool again and create a simple application that will retrieve a single record from Microsoft's sample database called ContosoRetailsDw. Make sure the DB is installed on your machine. Once done, we may now proceed in creating the sample program by performing the steps below.
Project Setup
1. Start off by creating a .NET Core Console Application targetting the latest framework which is .NET 5.02. Add three new folders Models, Repository and UnitOfWork. These folders contain the models and DAL classes used in this project. 3. Add the following NuGet packages: Microsoft.EntityFrameworkCore,Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Tools, System.Configuration.ConfigurationManager and Unity IoC container. 4. Reverse Engineer the ContosoRetailsDW by running the Scaffold-DbContext in Package Manager Console as we will use the Database First Approach. Replace the Server attribute with your default server.
PM> Scaffold-DbContext "Server=Your_Server;Database=ContosoRetailDW;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Data Access,Repositories And Unit Of Work
In this section, we will tackle the classes and interfaces that interacts with the ContosoRetailsDW database. The design patterns invloved are basically Repository and Unit Of Work. For this demo, I will only query a single record of the Employee table. Therefore, eliminating the other CRUD functionalities such as Create, Update and Delete.
1. First, we need to have a base repository that contains a get by id method that returns a generic type.
public interface IRepository<T> where T : class{ T GetByID(int Id); }
2. Next is to create a generic repository that defines a ContosoRetailDWContext variable that is responsible for communicating with the database and this class inherits the IRepository interface and implement the GetByID() method.
public class GenericRepository<T> : IRepository<T> where T : class{ private ContosoRetailDWContext _context; public GenericRepository() { this._context = new ContosoRetailDWContext(); } public T GetByID(int Id) { return _context.Set<T>().Find(Id); } }
public interface IEmployeeRepository : IRepository<DimEmployee> { //you may add other methods here specific to employees. }
public class EmployeeRepository : GenericRepository<DimEmployee>, IEmployeeRepository { public EmployeeRepository() { } }
public interface IUnitOfWork { IEmployeeRepository EmployeeRepository { get; } }
public class UnitOfWork : IUnitOfWork { public IEmployeeRepository EmployeeRepository { get; private set; } public UnitOfWork(IEmployeeRepository employeeRepository) { EmployeeRepository = employeeRepository; } }
Registering and Resolving Types
The UnityContainerResolver class below will resolve the dependencies that includes the service type and it's class. The RegisterType() method maps an interface to a specific class. This means that the Unity IoC container will automatically inject a specific object of a type to the interface. An example is the IUnitOfWork interface will then be mapped to a UnitOfWork class through constructor injection. The Resolve() method sorts out the types and executes the constructor injection.
public class UnityContainerResolver { private UnityContainer container; public UnityContainerResolver() { container = new UnityContainer(); RegisterTypes(); } public void RegisterTypes() { container.RegisterType(typeof(IRepository<>), typeof(GenericRepository<>)); container.RegisterType<IEmployeeRepository, EmployeeRepository>(); container.RegisterType<IUnitOfWork, UnitOfWork.UnitOfWork>(); } public UnitOfWork.UnitOfWork Resolver() { return container.Resolve<UnitOfWork.UnitOfWork>(); } }
Running The Application
In our Program.cs class, we need to create two static objects specifically UnitOfWork and UnityContainerResolver. The UnityContainerResolver object needs to be instantiated first in the Main() method before using it. Next is to create a ShowEmployee() method which will fetch the record from the database. The first code statement of the method will call the UnityContainerResolver Resolver() method and cast that into a UnitOfWork object.The UnitOfWork object will then execute the GetByID() method of the employee repository class by passing an existing employee id to the function's parameter and store the result in an employee object.
class Program { private static IUnitOfWork _unitOfWork; private static UnityContainerResolver _resolver; static void Main(string[] args) { _resolver = new UnityContainerResolver(); Console.WriteLine($"\n-----------------------------Employee Record-----------------------------"); ShowEmployee(); Console.ReadLine(); } static void ShowEmployee() { _unitOfWork = (IUnitOfWork)_resolver.Resolver(); var emp = _unitOfWork.EmployeeRepository.GetByID(1); Console.WriteLine($"Employee Name: { emp.FirstName} " + $"{ emp.LastName}, Employee Email: {emp.EmailAddress} "); } }
Output
Source Code: Unity IOC Container Demo
Comments
Post a Comment