.NET核心依赖项注入与静态

时间:2020-06-28 15:06:05

标签: c# asp.net-core .net-core dependency-injection static

我正在使用.net core3构建API。

在控制器中,我曾经使用静态类从sql获取信息列表或从webservices获取一些结果。

但是我认为使用依赖注入可能会更好。所以我更改了代码以使用DI。

但是我不确定这些更改实际上是否更好,如果可以,为什么?

请问它们有什么不同,哪一个更好?

原始代码:

    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" });
        }
    }

我更改了代码以使用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" });
        }
    }

在启动中

services.AddScoped<ISearchService, SearchService>();
services.AddScoped<IProductService, ProductService>();

1 个答案:

答案 0 :(得分:0)

带DI的版本更好。原因如下:

  1. 您可以注入不同的实现,而无需更改控制器代码
  2. 使用DI测试代码并不那么困难(使用静态类通常是不可能的)
  3. 静态类主要是全球性的。有状态的静态类可能会像其他语言中的全局变量一样起作用,从而可能产生无法预测的问题
  4. 通过检查控制器的控制器很容易猜出控制器的深度
  5. 使用DI控制数据库连接也变得不那么困难(例如,您可以使用存储库和工作单元模式,仅在需要时才打开与db的连接)
  6. 使用DI可以轻松扩展方法的行为。例如,您可能需要从本地缓存而不是从数据库返回数据。使用DI可以使用装饰器为您的服务完成,而使用静态类时,即使您只需要在代码的单个位置进行缓存,也必须修改此类本身。

我还要补充一点,到处都使用静态类不是OOP方法。因此,我建议改用类和DI的实例