.NET Core IOC container in extension methods

Introduction

In this article, we will create an IOC container as an extension method in .net core 2.2. 

Why

In the large project, when we create many services and repositories it's difficult to manage IOC container inside the one project and also IOC container cannot be share.

Suppose you are making a solution where you have windows from application, Web API application, Web application, mobile application (xamarin) , windows service application and you are trying to use your services from every application. But if you create IOC container inside the one application you can not resolve service dependency from everywhere.

So here will create an external library and inside this library, we will create an extension method and this extension method manage our service container. This way we can reuse our container into another project without any changes also this IOC container can be share every application. It will give us more flexibility to control our services. Before we start anything at first, we have to know what is dependency injection.

Dependency injection

Dependency injection is one form of the broader technique of inversion of control. The client delegates the responsibility of providing its dependencies to external code (the injector). The client is not allowed to call the injector code. it is the injecting code that constructs the services and calls the client to inject them. This means the client code does not need to know about the injecting code, how to construct the services or even which actual services it is using; the client only needs to know about the intrinsic interfaces of the services because these define how the client may use the services. This separates the responsibilities of use and construction. Read More

Setting up the project

Now start to the main point. At first, create an asp.net core 2.2 web API application. Here we are using Visual Studio 2019 IDE.



Here we successfully created our api application. Our solution name is CoreDI.


Now create a two Class Library(.NET Core) projects. The first-class library name is DAL, where we will create our repository. And the second class library project name is DI, here will create our extension method.

 

In the DAL project, we will create a folder, give the folder name Interface. In the interface folder create an interface and name it IValueRepository.cs and put the following code in it.

namespace DAL.Interface
{
    public interface IValueRepository
    {
        string[] GetValues();
    }
}

Now create a class into DAL project and name it ValueRepository.cs and put the following code in it.

using DAL.Interface;
 
namespace DAL
{
    public class ValueRepository : IValueRepository
    {
        public string[] GetValues()
            => new string[] { "valueFromRepository1", "valueFromRepository2" }; 
    }
}

After that DAL project look like this image


Now focus on DI Project. Create a class into DI project and name it ServiceContainer.cs and put the following code in it.

using DAL;
using DAL.Interface;
using Microsoft.Extensions.DependencyInjection;
 
namespace DI
{
    public static class ServiceContainer
    {
        public static void BuildServiceContainer(this IServiceCollection services)
        {
            services.AddSingleton<IValueRepository, ValueRepository>();
        }
    }
}

This place is the service container where we will mention which interface will locate which service. We have successfully created our extension method. Our extension method name is BuildServiceContainer.

Register

Now focus on CoreDI projects Startup.cs class. Here we can see the ConfigureServices method. Here we will register our IOC container which we have already created into DI project. So write this code inside the ConfigureServices method

 services.BuildServiceContainer();

Now ConfigureServices method looks like this. 

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.BuildServiceContainer(); 
}

Now we will use dependency injection in our controller. So, go to the ValuesController.cs and inject the IValueRepository interface. Put the following code in it.


using System.Collections.Generic;
using DAL.Interface;
using Microsoft.AspNetCore.Mvc;
 
namespace CoreDI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly IValueRepository _valueRepository;
        public ValuesController(IValueRepository valueRepository)
        {
            _valueRepository = valueRepository;
        }
        // GET api/values
        [HttpGet]
        public ActionResult> Get()
            => _valueRepository.GetValues();
    }
}

Now run the application and test it. For testing API, we have used postman. Let's see.


This API working successfully. Now, this way we can separate our Service collection or IOC container. In the large project, it will give us more flexibility.

Source Code

Get the source code from GitHub.

Next Article

In the next article, we will see how to unit test our created API and repository. Read this article  .NET Core Unit Test With Resolve Service Dependency.

Post a Comment

1 Comments