依赖注入的基本使用1/Program.cs
using Microsoft.Extensions.DependencyInjection;
ServiceCollection services = new ServiceCollection();
// 瞬态服务
services.AddTransient<TestServiceImpl>(); // => false
// 作用域服务
// services.AddScoped<TestServiceImpl>(); // => true
// 单例服务
// services.AddSingleton<TestServiceImpl>(); // => true
using (ServiceProvider sp = services.BuildServiceProvider())
{
// 服务定位器
var ts1 = sp.GetRequiredService<TestServiceImpl>();
var ts2 = sp.GetRequiredService<TestServiceImpl>();
Console.WriteLine(object.ReferenceEquals(ts1, ts2));
}
- 核心代码
依赖注入的基本使用1/TestServiceImpl2.cs
public class TestServiceImpl2 : ITestService
{
public string Name { get; set; }
public void SayHi()
{
Console.WriteLine($"你好,我是{Name}");
}
}
依赖注入的基本使用1/TestServiceImpl.cs
public class TestServiceImpl : ITestService
{
public string Name { get; set; }
public void SayHi()
{
Console.WriteLine($"Hi, I'm {Name}");
}
}
依赖注入的基本使用1/ITestService.cs
public interface ITestService
{
public string Name { get; set; }
public void SayHi();
}
标签:定位器,依赖,Name,services,dotnet,ITestService,public,cs
From: https://www.cnblogs.com/zhuoss/p/18012630