.NET Core 中依赖注入的使用

ASP.NET Core中服务注入的地方

  1. 在ASP.NET Core项目中一般不需要自己创建ServiceCollection、IServiceProvider。在Program.cs的builder.Build()之前向builder.Services中注入。
  2. 在Controller中可以通过构造方法注入服务。

低使用频率的服务

  1. 把Action用到的服务通过Action的参数注入,在这个参数上标注[FromServices]。和Action的其他参数不冲突。
  2. 一般不需要,只有调用频率不高并且资源的创建比较消耗资源的服务才[FromServices]。
  3. 只有Action方法才能用[FromServices] ,普通的类默认不支持。
cs 复制代码
public class student
{
    public int add(int a, int b)
    {
        return a + b;
    }
}

program:
builder.Services.AddScoped<student>();

[Route("api/[controller]/[action]")]
[ApiController]
public class LoginController : ControllerBase
{
    private readonly student students;

    public LoginController(student students)
    {
        this.students = students;
    }

    [HttpGet]
    public int abc(int id)
    {
        return new student().add(1, 2);
    }
}

开发模块化的服务注册框架

在分层项目中,让各个项目负责各自的服务注册。

  1. Install-Package Zack.Commons
  2. 每个项目中创建一个或者多个实现了IModuleInitializer接口的类。
  3. 在Program.cs初始化DI容器

var assemblies = ReflectionHelper.GetAllReferencedAssemblies();

builder.services.RunModuleInitializers(assemblies);

cs 复制代码
namespace ClassLibrary1
{
    public class Class1
    {
        public int Hello()
        {
            return 1;
        }
    }
}

namespace ClassLibrary1
{
    internal class ModuleInitializer : IModuleInitializer
    {
        public void Initialize(IServiceCollection services)
        {
            services.AddScoped<Class1>();
        }
    }
}

namespace WebApplication2.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PersonController : ControllerBase
    {
        private readonly Class1 class1;
        private readonly Class2 class2;

        public PersonController(Class1 class1, Class2 class2)
        {
            this.class1 = class1;
            this.class2 = class2;
        }

        [HttpGet]
        public int Hello()
        {
            return class1.Hello();
        }
    }
}

//Program添加
//获取所有的用户程序集
var assemblies = ReflectionHelper.GetAllReferencedAssemblies();
//扫描指定程序集中所有实现了IModuleInitializer接口的类,并调用Initialize方法完成服务注册
builder.Services.RunModuleInitializers(assemblies);
相关推荐
观无12 小时前
Windows 本地电脑搭建一个私有的、类似 Gitee 的 Git 服务
gitee·jenkins·.netcore
武藤一雄2 天前
C# 异常(Exception)处理避坑指南
windows·microsoft·c#·.net·.netcore·鲁棒性
csdn_aspnet4 天前
在 ASP.NET Core 中使用自定义属性实现 HTTP 请求和响应加密
http·asp.net·.netcore
观无4 天前
.NET Core + Ocelot 网关 跨域 (CORS) 配置
状态模式·.netcore
csdn_aspnet4 天前
如何在 .NET Core WebAPI 和 Javascript 应用程序中安全地发送/接收密钥参数
javascript·.netcore·cryptojs
武藤一雄6 天前
C# 异步回调与等待机制
前端·microsoft·设计模式·微软·c#·.netcore
武藤一雄7 天前
C#万字详解 栈与托管堆 的底层逻辑
windows·microsoft·c#·.net·.netcore
武藤一雄7 天前
深入拆解.NET内存管理:从GC机制到高性能内存优化
windows·microsoft·c#·.net·wpf·.netcore·内存管理
武藤一雄9 天前
WPF/C# 应对消息洪峰与数据抖动的 8 种“抗压”策略
windows·微软·c#·wpf·.netcore·防抖·鲁棒性
武藤一雄10 天前
C# 竟态条件
microsoft·c#·.net·.netcore