//依赖注入学习,使用构造函数,将创建对象交由DI容器来完成和管理
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<Worker>();
builder.Services.AddSingleton<IMessageWriter, MessageWriter>();
using IHost host = builder.Build();
host.Run();
public interface IMessageWriter
{
void Write(string message);
}
public class MessageWriter : IMessageWriter
{
public void Write(string message)
{
Console.WriteLine($"MessageWriter.Write(消息: \"{message}\")");
}
}
public sealed class Worker : BackgroundService
{
private readonly IMessageWriter _messageWriter;
public Worker(IMessageWriter messageWriter) =>
_messageWriter = messageWriter;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_messageWriter.Write($"Worker running at: {DateTimeOffset.Now}");
await Task.Delay(1_000, stoppingToken);
}
}
}
另一个例子,说明Transient、Scoped、Singleton生存期的不同
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddTransient<IExampleTransientService,ExampleTransientService>();
builder.Services.AddScoped<IExamplScopedService,ExampleScopedService>();
builder.Services.AddSingleton<IExamplSingetonService,ExampleSingletonService>();
builder.Services.AddTransient<ServiceLifetimeReporter>();
IHost host = builder.Build();
ExemplifyServiceLifetime(host.Services, "生存期 1");
ExemplifyServiceLifetime(host.Services, "生存期 2");
await host.RunAsync();
static void ExemplifyServiceLifetime(IServiceProvider hostProvider, string lifetime)
{
using IServiceScope serviceScope = hostProvider.CreateScope();
IServiceProvider provider = serviceScope.ServiceProvider;
ServiceLifetimeReporter logger = provider.GetRequiredService<ServiceLifetimeReporter>();
logger.ReportServiceLifetimeDetails(
$"{lifetime}: 请调用1至提供商。GetRequiredService<ServiceLifetimeReporter>");
Console.WriteLine("...");
logger = provider.GetRequiredService<ServiceLifetimeReporter>();
logger.ReportServiceLifetimeDetails(
$"{lifetime}: 请调用2至提供商。GetRequiredService<ServiceLifetimeReporter>");
Console.WriteLine();
}
internal sealed class ServiceLifetimeReporter
{
private readonly IExampleTransientService _transientService;
private readonly IExamplScopedService _scopedService;
private readonly IExamplSingetonService _singletonService;
public ServiceLifetimeReporter(
IExampleTransientService transientService,
IExamplScopedService scopedService,
IExamplSingetonService singetonService)=>
(_transientService, _scopedService, _singletonService) =
(transientService, scopedService, singetonService);
public void ReportServiceLifetimeDetails(string lifetimeDetails)
{
Console.WriteLine(lifetimeDetails);
LogService(_transientService, "总是与众不同");
LogService(_scopedService, "仅随生存期更改");
LogService(_singletonService, "总是一样");
}
private static void LogService<T>(T service, string message)
where T:IReportServiceLifetime
{
Console.WriteLine($"{typeof(T).Name}:{service.Id}({message})");
}
}
internal sealed class ExampleTransientService : IExampleTransientService
{
public Guid Id { get; } = Guid.NewGuid();
}
internal sealed class ExampleScopedService : IExamplScopedService
{
public Guid Id { get; } = new Guid();
}
internal sealed class ExampleSingletonService : IExamplSingetonService
{
public Guid Id { get; } = new Guid();
}
public interface IReportServiceLifetime
{
/// <summary>
/// 表示服务的唯一标识符的 Guid Id 属性
/// </summary>
Guid Id { get; }
/// <summary>
/// 表示服务生存期的 ServiceLifetime 属性。
/// </summary>
ServiceLifetime Lifetime { get; }
}
/// <summary>
/// 暂时性服务
/// </summary>
public interface IExampleTransientService : IReportServiceLifetime
{
ServiceLifetime IReportServiceLifetime.Lifetime => ServiceLifetime.Transient;
}
/// <summary>
/// 范围服务
/// </summary>
public interface IExamplScopedService : IReportServiceLifetime
{
ServiceLifetime IReportServiceLifetime.Lifetime => ServiceLifetime.Scoped;
}
/// <summary>
/// 单例服务
/// </summary>
public interface IExamplSingetonService : IReportServiceLifetime
{
ServiceLifetime IReportServiceLifetime.Lifetime => ServiceLifetime.Singleton;
}
独学而无友,则孤陋而寡闻。
浙公网安备 33010602011771号