How to use Dependency Injection in ASP.NET Core

By FoxLearn 2/18/2024 9:06:48 AM   185
ASP.NET Core is designed from the ground up to support and leverage dependency injection

In this post i'll show you how to use dependency injection in ASP.NET Core.

Dependency injection (DI) is a technique for achieving loose coupling between objects and their collaborators, or dependencies. Rather than directly instantiating collaborators, or using static references, the objects a class needs in order to perform its actions are provided to the class in some fashion.

Open Visual Studio->File->New->Project->Select ASP.NET Core Web Application template

We will create a simple repository to insert update delete data to our database

public class Company
{
    public Guid Id { get; set; }
    public string CompanyName { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string Fax { get; set; }
    public string TaxId { get; set; }
    public string AccountNumber { get; set; }
    public string BankName { get; set; }
    public string Email { get; set; }
    public string Website { get; set; }
}

Create a generic interface as below

public interface IRepository<T> where T : class
{
    List<T> GetAll();
    Guid Insert(T obj);
    bool Update(T obj);
    bool Delete(Guid id);
}

Create an interface, then inheritance IRepository

public interface ICompanyRepository : IRepository<Company>
{
}

Create a repository class then implement ICompanyRepository interface, we alway use interface to call methods

public class CompanyRepository : ICompanyRepository
{
    public bool Delete(Guid id)
    {
        throw new NotImplementedException();
    }

    public List<Company> GetAll()
    {
        throw new NotImplementedException();
    }

    public Guid Insert(Company obj)
    {
        throw new NotImplementedException();
    }

    public bool Update(Company obj)
    {
        throw new NotImplementedException();
    }
}

Open Startup class, then add a config service as below to the ConfigureServices method

services.AddTransient<ICompanyRepository, CompanyRepository>();

There are three options for DI container in ASP.NET Core:

Singleton: Only a single instance will be created and shared

Scoped: An instance is created once per scope

Transient: Create every time they are requested and are never shared.

services.AddScoped<ICompanyRepository, CompanyRepository>();
services.AddSingleton<ICompanyRepository, CompanyRepository>();

To use DI you need to create a controller, then add code as below

public class CompanyController : Controller
{
    private readonly ICompanyRepository _companyRepository;

    public CompanyController(ICompanyRepository companyRepository)
    {
        _companyRepository = companyRepository;
    }    

    [HttpGet]
    public JsonResult GetAll()
    {
        return Json(_companyRepository.GetAll(), JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public JsonResult Create(Company obj)
    {
        return Json(new { id = _companyRepository.Insert(obj) });
    }

    [HttpPut]
    public JsonResult Update(Company obj)
    {
        return Json(new { success = _companyRepository.Update(obj) });
    }

    [HttpDelete]
    public JsonResult Delete(Guid id)
    {
        return Json(new { success = _companyRepository.Delete(id) });
    }
}