先上一段官方文档概括一下依赖注入的实现
- 使用接口或基类将依赖关系实现抽象化。
- 在服务容器中注册依赖关系。 ASP.NET Core 提供了一个内置的服务容器 IServiceProvider。 服务通常已在应用的
Program.cs
文件中注册。 - 将服务注入到使用它的类的构造函数中。 框架负责创建依赖关系的实例,并在不再需要时将其释放。
个人理解:
类A依赖类B,在行为上是在类A中需要实例化(new)类B来使用它的内容。这一段关系称为依赖关系。那么实现依赖注入就是:实现类继承服务类(接口),并实现它的方法将它注册到容器中,在通过构造函数注入,由容器来实例化并管理(生命周期)。
仅供参考,官网原文为主
上手操作:
创建一个接口
namespace demo.Services
{
public interface IStudent
{
public void write(string a);
}
}
创建一个类继承接口
using demo.Services;
namespace demo.DAL
{
public class Student : IStudent
{
public void write(string b)
{
Console.WriteLine($"MyDependency.WriteMessage Message: {b}");
}
}
}
在program文件中注册到容器
using demo.DAL;
using demo.Services;
namespace demo
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
//这里使用了一个生命周期Scoped为范围内,生命周期解释参考原文
//应该有其他注册到容器的方法,还没学会。
//个人问题,如果有很多类和对应的接口,难道要每个注册一次?
builder.Services.AddScoped<IStudent, Student>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
}
}
}
通过构造函数注入
public class IndexModel : PageModel
{
public string str { get; set; }
private readonly ILogger<IndexModel> _logger;
private readonly IStudent _student;
public IndexModel(ILogger<IndexModel> logger, IStudent student)
{
_logger = logger;
_student = student;
}
public void OnGet()
{
_student.write("这是打印数据");
}
}