.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);
相关推荐
武藤一雄7 小时前
.NET 中常见计时器大全
microsoft·微软·c#·.net·wpf·.netcore
武藤一雄1 天前
[.NET] 中 System.Collections.Generic命名空间详解
windows·微软·c#·asp.net·.net·.netcore
van久5 天前
.Net Core 学习:Razor Pages中 HTML 表头字段的两种写法对比
学习·html·.netcore
武藤一雄5 天前
C# 万字拆解线程间通讯?
后端·微软·c#·.net·.netcore·多线程
武藤一雄6 天前
.NET中到底什么是SignalR (持续更新)
后端·微软·c#·asp.net·.net·.netcore·signalr
by__csdn6 天前
第二章 (.NET Core环境搭建)第二节( Visual Studio Code)
ide·vscode·c#·vue·asp.net·.net·.netcore
by__csdn6 天前
第二章 (.NET Core环境搭建)第三节( Visual Studio for Mac)
ide·kubernetes·c#·asp.net·.net·.netcore·visual studio
武藤一雄8 天前
C#:进程/线程/多线程/AppDomain详解
后端·微软·c#·asp.net·.net·wpf·.netcore
武藤一雄8 天前
C#:Linq大赏
windows·后端·microsoft·c#·.net·.netcore·linq
by__csdn8 天前
第一章 (ASP.NET Core入门)第三节( 认识.NET Standard)
后端·c#·asp.net·.net·.netcore·f#·vb.net