编辑
2025-09-24
C#
00

目录

摘要
正文

摘要

在C#中,可以使用依赖注入容器(Dependency Injection Container)来根据类型获取和注册服务。依赖注入是一种设计模式,它允许我们将对象的创建和依赖解析从使用它的类中分离出来,从而实现松耦合和可测试性。

正文

服务类型可以是类,也可以是接口,不过推荐使用接口,要录活些。

  • Install-Package Microsoft.Extensions.DependencyInjection
  • using Microsoft.Extensions.DependencyInjection
  • SerivceCollection构造容器对象 IServiceProvider
  • BuildServiceProvider()创建ServiceProvider

image.png

一个例子

我们做了一个接口,然后用Plc继承了这个接口。

C#
internal class Program { static void Main(string[] args) { IEquipment plc = new Plc() { Name = "S71200", Description = "SIEMENS S7" }; plc.Read("DB0.0"); } } interface IEquipment { public string Name { get; set; } public string Description { get; set; } public void Read(string address); } class Plc : IEquipment { public string Name { get; set; } public string Description { get; set; } public void Read(string address) { Console.WriteLine(this.Name + " " + address + " " + new Random().Next(1, 200)); } }

修改成注册服务

C#
static void Main(string[] args) { ServiceCollection services = new ServiceCollection(); services.AddTransient<Plc>(); using (ServiceProvider sp = services.BuildServiceProvider()) { Plc plc= sp.GetService<Plc>(); plc.Name = "S71200"; plc.Description = "SIEMENS"; plc.Read("DB0.0"); }; }

好像代码多了一堆!没感觉好处在哪里?

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!