.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);
相关推荐
weixin_379880926 天前
.Net Core WebApi集成Swagger
java·服务器·.netcore
The Future is mine8 天前
.Net Core 在Linux系统下创建服务
linux·运维·.netcore
*长铗归来*9 天前
ASP.NET Core Web API 中控制器操作的返回类型及Swagger
后端·c#·asp.net·.netcore
IDOlaoluo9 天前
VS2017 安装 .NET Core 2.2 SDK 教程(包括 dotnet-sdk-2.2.108-win-x64.exe 安装步骤)
.netcore
csdn_aspnet17 天前
使用 Entity Framework Code First 方法创建 ASP.NET Core 5.0 Web API
.netcore·webapi
小先生81217 天前
.NET Core项目中 Serilog日志文件配置
c#·.netcore
爱吃香蕉的阿豪17 天前
.NET Core 中 System.Text.Json 与 Newtonsoft.Json 深度对比:用法、性能与场景选型
数据库·json·.netcore
csdn_aspnet17 天前
ASP.NET Core 10.0 的主要变化
.netcore
csdn_aspnet20 天前
在 C# .NETCore 中使用 MongoDB(第 1 部分):驱动程序基础知识和插入文档
mongodb·.netcore
csdn_aspnet20 天前
在 C# .NETCore 中使用 MongoDB(第 3 部分):跳过、排序、限制和投影
mongodb·c#·.netcore