

.net 温故知新【13】:Asp.Net Core WebAPI 使用依赖注入DI - XSpringSun
source link: https://www.cnblogs.com/SunSpring/p/17816564.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、使用DI注入
在之前的文章中已经讲过DI的概念(.net 温故知新:【7】IOC控制反转,DI依赖注入),基于控制台程序演示了DI依赖注入的使用,基于Microsoft.Extensions.DependencyInjection
完成。那在WebAPI中如何使用依赖注入呢?
首先新建一个WebAPI项目WebAPI_DI
,框架.net 7,其实 webapi 项目也是控制台应用程序,只是在Asp.Net Core webapi框架中很多基础工作已经帮我们封装配置好了。
项目新建完成后在Program.cs 中自动生成如下代码:
namespace WebAPI_DI
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}
builder.Services
则是帮我已经创建好的IServiceCollection
对象。
我们再新建一个测试类 DITestClass:
public class DITestClass
{
public int Add(int i, int n)
{
return i + n;
}
}
然后我们在builder.Services中进行注册

最后我们在默认的WeatherForecastController
控制器里面加一个post方法,并用构造函数注入的方式将DITestClass注入进去。

swagger中调用测试:

二、[FromService] 注入
FromServicesAttribute 允许将服务直接注入到操作方法,而无需使用构造函数注入。
改属性的作用主要针对我们在依赖注入初始化对象(该对象初始化很耗时),这个时候不管请求的api方法有没有用到该对象都会等待很长时间。
所以使用FromService让接口在请求的时候再注入,从而不影响其他接口

三、多层架构注入
在多层架构中我们如果引用了其他项目,要使用其他项目中的类,那么要在主项目中进行DI注入,这样相当于所有其他模块或者其他人写的项目都需要主项目来维护注入,比如:
新建一个ClassLibrary1项目,Class1类,方法Sub:

我们在web项目里面引用ClassLibrary1项目,如果要使用Class1类就需要在 Programe.cs里面注册
builder.Services.AddScoped(typeof(Class1));

那么有没有方法让他们自己的项目自己管理注册呢,我们可以简单改造一下
- 新建一个类库,定义一个公共接口,安装
Microsoft.Extensions.DependencyInjection
包

- 在ClassLibarary1里面定义实现接口类
public class ModulInit : IModuleInit
{
public void Init(IServiceCollection service)
{
//所有需要DI的在此处注入
service.AddScoped<Class1>();
}
}
- 在Programe.cs里面调用引用项目的注册类

这样其他项目也按照这种方式,在主项目中只要调用一次注册管理。不过这是最简单的方式,你也可以使用反射来查找引用的项目继承了IModuleInit
的类,然后进行Init
方法调用,这样会更优雅一些。
当然你还可以使用其他依赖注入框架来取代Microsoft.Extensions.DependencyInjection
,也许这个问题就不再是问题!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK