3

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>();
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
dbenbyeon
  • 145
  • 2
  • 6
  • Reference [Dependency injection in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection) – Nkosi Jun 28 '20 at 15:54

1 Answers1

8

Version with DI is better. There are some reasons:

  1. You can inject different implementations without any need to change your controller code
  2. It's less difficult to test code with DI (with static classes it's often impossible)
  3. Static classes are mostly global public. Stateful static classes could act like global variables in other languages that can produce unpredictable issues
  4. It's easy to guess dependencies of controller by checking its constructor
  5. Also it's less difficult to control db connection using DI (you can use repository and unit of work patterns for example, open connection to db only when it's needed)
  6. With DI it's easy to extend behavior of your method. For example, you might need to return data from local cache instead of db. With DI it could be done using decorator for your service, while with static class you will have to modify this class itself even if you need caching only in single place of your code

Also I wanna add that using static classes everywhere is not OOP approach. So I recommend to use instances of you classes and DI instead

Ruslan K.
  • 1,912
  • 1
  • 15
  • 18
ingvar
  • 4,169
  • 4
  • 16
  • 29