C#依赖注入(一)初识
使用没有依赖注入的服务
//代码文件 WithoutDi/GreetService.cs
public class GreetingSevice
{
public string Greet(string name) => $"Hello,{name}";
}
类HomeController使用服务
//代码文件 WithoutDi/HomeController.cs
public class HomeController
{
public string Hello(string name)
{
var service = new GreetingService();
service.Greet(name);
}
}
//主函数
static void Main()
{
var controller = new HomeConlller();
string result = controller.Hello("Stephanie");
Console.WriteLine(result

本文介绍了C#中依赖注入的概念,通过对比无依赖注入和使用依赖注入(构造函数注入方式)的区别,阐述了依赖注入能降低类之间的耦合度,方便单元测试。并详细讲解了如何在.NET Core中使用DI容器进行服务注册和生命周期管理,以及在运行时如何通过DI容器获取服务。
最低0.47元/天 解锁文章
618

被折叠的 条评论
为什么被折叠?



