Donate

Using Unity IoC Container Dependency Injection, Dapper ORM and SQL Server In Visual Basic .NET Core Or .NET 5 Application

Hi All,

This article is the VB.NET version of this post Getting Started With Unity IoC Container Dependency Injection In .NET Core Using Entity Framework Core ORM And SQL Server. We will create a .NET Core Console Application that will utilize the Unity IoC Container for Dependency Injection, SQL Server and Dapper ORM. Instead of using Entity Framework, I'm using Dapper ORM coz EF does not support reverse engineering in .NET Core. There are existing power tools or other solutions on how to reverse engineer a database table but for now I'll just use Dapper. I'll be using Microsoft's sample database called ContosoRetailsDw as the datasource of this tutorial.

Project Setup

1. Start off by creating a Visual Basic .NET Core Console Application targetting the latest framework which is .NET 5.0
2. Add three new folders Models, Repository and UnitOfWork. These folders contain the model and DAL classes used in this project.
Using Unity IoC Container Dependency Injection, Dapper ORM and SQL Server In Visual Basic .NET Core Or .NET 5 Application
3. Add the following NuGet packages: Dapper ORM, System.Data.SqlClient, System.Configuration.ConfigurationManager and Unity IoC container.
Using Unity IoC Container Dependency Injection, Dapper ORM and SQL Server In Visual Basic .NET Core Or .NET 5 Application
4. Set the connectionstring in app.config using the ContosoRetailDW database.
 <appSettings>
    <add key="ContosoDB" value="Server=Your_Server;Database=ContosoRetailDW;Integrated Security=True"/>
  </appSettings>

Coding The Model Class

Since we will be using Dapper ORM, we need to define the model class by ourselves. So add a class called Employee that has three properties and make sure that properties match the column names of the database table. This class is the object mapping of ContosoRetailsDW DimEmployee table.
Public Class Employee

    Private m_FirstName As String
    Public Property FirstName() As String
        Get
            Return m_FirstName
        End Get
        Set(value As String)
            m_FirstName = value
        End Set
    End Property

    Private m_LastName As String
    Public Property LastName() As String
        Get
            Return m_LastName
        End Get
        Set(value As String)
            m_LastName = value
        End Set
    End Property

    Private m_EmailAddress As String
    Public Property EmailAddress() As String
        Get
            Return m_EmailAddress
        End Get
        Set(value As String)
            m_EmailAddress = value
        End Set
    End Property
End Class

Data Access,Repositories And Unit Of Work

1. Let's start off by creating an interface called IEmployeeRepository that only has one function definition that retrieves a single record from the database and has a return type of Employee type.
Public Interface IEmployeeRepository
    Function FindById(Id As Integer) As Employee
End Interface
2. Define a repository class that implements the IEmployeeRepository interface and it's single FindById() function. This class will now employ Dapper ORM's awesome features that communicates the SQL Server database. As observed, this class has a SQLConnection object, a constructor that retrieves the connectionstring from app.config and the FindById() function. The FindById() function will fetch a single record from DimEmployee table using the EmployeeKey column. The result will then be stored onto an Employee object and return to the caller afterwards.
Option Strict On

Imports Dapper
Imports System.Configuration
Imports System.Data.SqlClient

Public Class EmployeeRepository
    Implements IEmployeeRepository

    Private _db As SqlConnection

    Public Sub New()
        Dim conn As String = ConfigurationManager.AppSettings("ContosoDB")
        _db = New SqlConnection(conn)
    End Sub

    Public Function FindById(Id As Integer) As Employee Implements IEmployeeRepository.FindById

        Dim empObject As New Employee()

        empObject = _db.Query(Of Employee)("SELECT * FROM DimEmployee WHERE EmployeeKey=@Id", New With {
            Key .Id = Id
        }).FirstOrDefault()

        Return empObject

    End Function

End Class
3. After creating the repository class and interface, we will then proceed with the Unit Of Work pattern. First is to create an IUnitOfWork interface with an EmployeeRepository property that is of type IEmployeeRepository.
Public Interface IUnitOfWork
    Property EmployeeRepository As IEmployeeRepository

End Interface
4. Next is to define the UnitOfWork class that inherits the IUnitOfWork interface. This class implements the EmployeeRepository property with a getter and setter accessors. The constructor of this class accepts an IEmployeeRepository parameter which will then be resolved by the Unity IoC container.
Public Class UnitOfWork
    Implements IUnitOfWork

    Public Sub New(employeeRepository As EmployeeRepository)
        Me.EmployeeRepository = employeeRepository
    End Sub

    Private p_IEmployeeRepository As IEmployeeRepository
    Public Property EmployeeRepository As IEmployeeRepository Implements IUnitOfWork.EmployeeRepository
        Get
            Return p_IEmployeeRepository
        End Get

        Set(value As IEmployeeRepository)
            p_IEmployeeRepository = value
        End Set
    End Property

End Class

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.
Option Strict On

Imports Unity

Public Class UnityContainerResolver
    Private container As UnityContainer

    Public Sub New()
        container = New UnityContainer()
        RegisterTypes()
    End Sub

    Public Sub RegisterTypes()
        container.RegisterType(Of IEmployeeRepository, EmployeeRepository)()
        container.RegisterType(Of IUnitOfWork, UnitOfWork)()
    End Sub

    Public Function Resolver() As UnitOfWork
        Return container.Resolve(Of UnitOfWork)()
    End Function
End Class

Running The Application

In our Program.vb module, we need to create two objects specifically UnitOfWork and UnityContainerResolver. The UnityContainerResolver object needs to be instantiated first in the Main() method before using it. Next is to add the logic that will fetch the record from the database. The next statement will call the UnityContainerResolver Resolver() method and cast that into a UnitOfWork object.The UnitOfWork object will then execute the FindById() 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.
Module Program

    Dim _unitOfWork As IUnitOfWork
    Dim _resolver As UnityContainerResolver

    Sub Main(args As String())

        _resolver = New UnityContainerResolver()

        Console.WriteLine($"\n-----------------------------Employee Record-----------------------------")

        _unitOfWork = CType(_resolver.Resolver(), IUnitOfWork)

        Dim emp = _unitOfWork.EmployeeRepository.FindById(1)
        Console.WriteLine($"Employee Name: { emp.FirstName} " + $"{ emp.LastName}, Employee Email: {emp.EmailAddress} ")

        Console.ReadLine()
    End Sub
End Module
When running the application, it should show the Employee record being displayed at the console window.
Using Unity IoC Container Dependency Injection, Dapper ORM and SQL Server In Visual Basic .NET Core Or .NET 5 Application

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.