.NET 依赖注入的3中方式

发布时间 2023-12-13 15:17:22作者: 木乃伊人

一、简介

       依赖注入共有3种方式:构造函数注入、属性注入、方法注入

二、构造函数注入

       在program.cs中对组件进行注册:     

builder.Services.AddScoped<IScopedService,ScopedService>();

       服务注册配置后,在需要注入的类上使用构造函数。

public class Controller
{
    private readonly IScopedService Service;
    public Controller(IScopedService service)
    {
        this.Service = service;
    }
}

三、属性注入  

定义接口和类,同构造函数注入。

public class Controller
{
    [Inject]
    private readonly IScopedService Service{get;set;}

//使用
Service 调用所需方法
    Service.GetMoney();
}

 

在Startup.cs文件的 Configure.Services 方法中,需要添加 AddControllersWithViews() 方法,并启用属性注入。

四、方法注入(比较少见)

定义接口和类,同构造函数注入。

在需要调用的方法中加上[Dependency]

public class Controller
{
private readonly IScopedService Service = null;//属性改为为变量
//新增任意名称方法,参数为需要注入的 IScopedService ,写法与构造函数类似,只是此处是方法不是构造函数。
public void Function( IScopedService service) { 
Service = service;
}

public void Hey(){
Service.GetMoney();
}