I am building an API with .net core3.
In the controller, I used to use static class to get a list of information from sql or get some results from webservices.
But I think it might be better to use dependency injection. So I changed the code to use DI.
But I am not sure the changes are actually better and if so, why?
Can I please get how they are different and which one is better?
Original code:
public class TestController : Controller
{
[HttpGet("{id}")]
public async Task<IActionResult> Product(int id)
{
///SearchManager is static class, static GetProductCodesFromSearch method get list of productcode from sql
List<string> productCodes = SearchManager.GetProducCodeFromSearch();
//ProductManager is static class, GetProducts mehtod make a webrequest as parallel to some webservice get list of product
List<Product> products = await ProductManager.GetProducts();
....
return Json(new { success = true, message = "Ok" });
}
}
and I changed the codes to use DI
public class TestController : Controller
{
private readonly ISearchService _searchService;
private readonly IProductService _productService;
public TestController( ISearchService searchService,IProductService productService)
{
_searchService = searchService;
_productService = productService;
}
[HttpGet("{id}")]
public async Task<IActionResult> Product(int id)
{
//searchservice class is not static class, not static method GetProductCodesFromSearch method get list of productcode from sql
List<string> productCodes = _searchService.GetProducCodeFromSearch();
// productservice is not static class, not static GetProducts mehtod make a webrequest as parallel to some webservice get list of product
List<Product> products = await _productService.GetProducts();
....
return Json(new { success = true, message = "Ok" });
}
}
In Startup
services.AddScoped<ISearchService, SearchService>();
services.AddScoped<IProductService, ProductService>();