Tuesday, January 7, 2020

AddSingleton vs AddScoped vs AddTransient methods - Dependency injection into controllers in .NET Core

The Model class

public class InventoryItems
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}

The interface for the service class

public interface IInventoryServices
{
InventoryItems AddInventoryItems(InventoryItems items);
Dictionary<string, InventoryItems> GetInventoryItems();
}

The service class

public class InventoryServices : IInventoryServices
{
private readonly Dictionary<string, InventoryItems> _inventoryItems;

public InventoryServices()
{
_inventoryItems = new Dictionary<string, InventoryItems>();
}
public InventoryItems AddInventoryItems(InventoryItems items)
{
_inventoryItems.Add(items.Name, items);
return items;
}

Dictionary<string, InventoryItems> IInventoryServices.GetInventoryItems()
{
return _inventoryItems;
}
}

The controller which the service is injected in the constructor

    [Route("api/[controller]")]
    [ApiController]
    public class InventoryController : ControllerBase
    {
private readonly IInventoryServices _service;

public InventoryController(IInventoryServices services)
{
_service = services;
}

[HttpPost]
[Route("AddInventoryItems")]
public ActionResult<InventoryItems> AddInventoryItem(InventoryItems items)
{
var inventoryItems = _service.AddInventoryItems(items);
return inventoryItems;
}

[HttpGet]
[Route("GetInventoryItems")]
public ActionResult<Dictionary<string, InventoryItems>> GetInventoryItems()
{
var inventoryItems = _service.GetInventoryItems();
return inventoryItems;
}
    }

Now in the Startup.cs we have to specify the dependency injection under the "ConfigureServices" method.

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IInventoryServices, InventoryServices>();
}

There are three ways in which you could set the Dependency Injection. They are AddSingleton(), AddScoped() and AddTransient()

Singleton - An instance of the service class (InventoryServices) is created, when the interface of the service (IInventoryServices) is first requested and that single instance of the service class (InventoryServices) is used by all http requests throughout the application

Scoped - Here we get the same instance within the scope of a given http request but a new instance of the service is created during a different http request

Transient - a new instance of the service class is created every time an instance is requested whether it is the scope of the same http request or across different http requests 

Auxiliary
Postman Post Request:









  

                                                                                                                                               
  
             Postman Get Request:



No comments:

Post a Comment