.NET 依赖注入的3中方式

一、简介

       依赖注入共有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();
}
复制代码

 

     

posted on   木乃伊人  阅读(402)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示