.NET Core 依赖注入-1
1.依赖注入(Dependency Injection,DI)是控制反转(Inversion Of Control,IOC)思想的实现方式。依赖注入简化模块的组装过程,降低模块质检的耦合度
需要引用到的NuGet包:Microsoft.Extensions.DependencyInjection
2.
public interface ITestService
{
public int Age { get; set; }
public string Name { get; set; }
void SayHi();
}
public class TestService : ITestService
{
public int Age { get; set; }
public string Name { get; set; }
public void SayHi()
{
Console.WriteLine(Name + Age);
}
}
ServiceCollection Services = new ServiceCollection();
//生命周期分为三种 Transient(瞬时)、Scope(作用域,推荐)、Singleton(单例)
Services.AddTransient<ITestService, TestService>();
//Services.AddTransient<typeof(ITestService), ty7peof(TestService)>();
//Services.AddTransient<typeof(ITestService), new TestService()>();
using (ServiceProvider provider = Services.BuildServiceProvider())
{
//T GetService<T>() 获取不到对象会返回null
// T GetRequiredService<T>() 获取不到对象会抛出异常
// IEnumerable<T>GetServices<T> 用于可能满足很多条件的服务
var t = provider.GetService<ITestService>();
t.Age = 111;
t.Name = "ss";
t.SayHi();
var t2 = provider.GetService<ITestService>();
t2.Age = 111;
t2.Name = "ssdsfcxzs";
t2.SayHi();
t.SayHi();
Console.WriteLine(object.ReferenceEquals(t, t2));
}
3.依赖注入具有传染性 如果一个类通过DI构造,那么这个类的构造函数中声明的所有服务器类型的参数都会被DI赋值
ServiceCollection services=new ServiceCollection();
services.AddScoped<ILog, ILogImpl>();
services.AddScoped<ILog, FileImpl>();
//同一个接口注入多个实现类 会被覆盖
services.AddScoped<IStorage, IStorageImpl>();
services.AddScoped<IController, Controller>();
using (ServiceProvider ServiceProvider = services.BuildServiceProvider())
{
var CONTYROL= ServiceProvider.GetService<IController>();
CONTYROL.Test();
}
interface IController
{
void Test();
}
class Controller : IController
{
private readonly ILog log;
private readonly IStorage storage;
public Controller(ILog log, IStorage storage)
{
this.log = log;
this.storage = storage;
}
public void Test()
{
log.WriteLog("ssssssss");
storage.WriteLog("2222222222");
}
}
interface ILog
{
void WriteLog(string content);
}
class ILogImpl : ILog
{
public void WriteLog(string content)
{
Console.WriteLine($"记录日志信息:{content}");
}
}
class FileImpl : ILog
{
public void WriteLog(string content)
{
Console.WriteLine($"通过文件记录日志信息:{content}");
}
}
interface IStorage
{
void WriteLog(string content);
}
class IStorageImpl : IStorage
{
public void WriteLog(string content)
{
Console.WriteLine($"上传文件到云盘:{content}");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!