Dependency Injection in ASP.NET Core
Creating the View Model
Create the Models
folder and create the following viewModel
.
public class ProductViewModel { public int Id { get; set; } public string Name { get; internal set; } }
Adding the Service
Create the folder Services
and add a class with the name ProductService.cs
.
using DependencyInjection.Models; using System.Collections.Generic; namespace DependencyInjection.Service { public interface IProductService { List<ProductViewModel> getAll(); } public class ProductService : IProductService { public List<ProductViewModel> getAll() { return new List<ProductViewModel> { new ProductViewModel {Id = 1, Name = "Pen Drive" }, new ProductViewModel {Id = 2, Name = "Memory Card" }, new ProductViewModel {Id = 3, Name = "Mobile Phone" }, new ProductViewModel {Id = 4, Name = "Tablet" }, new ProductViewModel {Id = 5, Name = "Desktop PC" } , }; } } }
Using the Service in Controller
using DependencyInjection.Service; using Microsoft.AspNetCore.Mvc; namespace DependencyInjection.Controllers { public class HomeController : Controller { private IProductService _productService; public HomeController(IProductService productService) { _productService = productService; } public IActionResult Index() { return View(_productService.getAll()); } } }
Register the Service
The last step is to register the service in the Dependency Injection container.
Open the startup.cs
and goto to ConfigureServices
method. This is where all services are configured for dependency injection.
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddTransient<IProductService, ProductService>(); }
Managing the Service Lifetime
There are three ways, by which you can do that. And it in turn decides how the DI Framework manages the lifecycle of the services.
- Transient: creates a new instance of the service, every time you request it.
- Scoped: creates a new instance for every scope. (Each request is a Scope). Within the scope, it reuses the existing service.
- Singleton: Creates a new Service only once during the application lifetime, and uses it everywhere
services.AddTransient<ITransientService, SomeService>();
services.AddScoped<IScopedService, SomeService>();
services.AddSingleton<ISingletonService, SomeService>();
References
https://www.tektutorialshub.com/asp-net-core/asp-net-core-dependency-injection/
https://www.tektutorialshub.com/asp-net-core/asp-net-core-dependency-injection-lifetime/