依赖注入的基本使用1/Program.cs
using Microsoft.Extensions.DependencyInjection;
ServiceCollection services = new ServiceCollection();
// AddTransient的两种方式
// services.AddTransient<ITestService,TestServiceImpl>();
// services.AddTransient(typeof(ITestService),typeof(TestServiceImpl));
// AddSingleton的三种方式
// services.AddSingleton<ITestService,TestServiceImpl>();
// services.AddSingleton(typeof(ITestService),new TestServiceImpl());
services.AddSingleton<ITestService>(new TestServiceImpl());
// AddScoped的三种方式
// services.AddScoped<ITestService, TestServiceImpl>();
using (ServiceProvider sp = services.BuildServiceProvider())
{
var ts1 = sp.GetRequiredService<ITestService>();
ts1.Name = "Alice";
ts1.SayHi();
}
依赖注入的基本使用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();
}