• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
安绍峰
独学而无友,则孤陋而寡闻。
博客园    首页    新随笔    联系   管理    订阅  订阅
依赖注入
//依赖注入学习,使用构造函数,将创建对象交由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;
}
独学而无友,则孤陋而寡闻。
posted on 2023-11-08 13:41  安绍峰  阅读(43)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3