You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core依赖注入中两种服务注册方式的优劣对比

两种IIntegrationEventLogService依赖注入方式的对比疑问

我一直找不到这个问题的答案,有人曾提出类似问题但没得到充分解答,希望能有人帮我理解。

第一种注入方式

为什么要采用这种写法?

services.AddTransient<Func<DbConnection, IIntegrationEventLogService>>(
            sp => (DbConnection c) => new IntegrationEventLogService(c));

第二种注入方式

而非这种写法?

services.AddTransient<IIntegrationEventLogService, IntegrationEventLogService> (sp =>
    {
        var bookCatalogueDbContext = sp.GetRequiredService<BookCatalogueDbContext>();
        var dbConnection = bookCatalogueDbContext.Database.GetDbConnection();

        return new IntegrationEventLogService(dbConnection);
    });

第一种方式的调用代码

private readonly Func<DbConnection, IIntegrationEventLogService> _integrationEventLogServiceFactory;
private readonly IEventBus _eventBus;
private readonly BookCatalogueDbContext _bookCatalogueDbContext;
private readonly IIntegrationEventLogService _eventLogService;
private readonly ILogger<BookCatalogueIntegrationEventService> _logger;
private volatile bool disposedValue;

public BookCatalogueIntegrationEventService(
    IEventBus eventBus,
    ILogger<BookCatalogueIntegrationEventService> logger,
    BookCatalogueDbContext bookCatalogueDbContext,
    Func<DbConnection, IIntegrationEventLogService> integrationEventLogServiceFactory)
{
    _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    _bookCatalogueDbContext = bookCatalogueDbContext ?? throw new ArgumentNullException(nameof(bookCatalogueDbContext));
    _integrationEventLogServiceFactory = integrationEventLogServiceFactory ?? throw new ArgumentNullException(nameof(integrationEventLogServiceFactory));
    _eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus));
    _eventLogService = _integrationEventLogServiceFactory(_bookCatalogueDbContext.Database.GetDbConnection());  
}

第二种方式的调用代码

private readonly IIntegrationEventLogService _integrationEventLogService;
private readonly IEventBus _eventBus;
private readonly BookCatalogueDbContext _bookCatalogueDbContext;
private readonly ILogger<BookCatalogueIntegrationEventService> _logger;
private volatile bool disposedValue;

public BookCatalogueIntegrationEventService(
    IEventBus eventBus,
    ILogger<BookCatalogueIntegrationEventService> logger,
    BookCatalogueDbContext bookCatalogueDbContext,
    IIntegrationEventLogService integrationEventLogService)
{
    _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    _bookCatalogueDbContext = bookCatalogueDbContext ?? throw new ArgumentNullException(nameof(bookCatalogueDbContext));
    _eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus));
    _integrationEventLogService = integrationEventLogService;  
}

请问第一种方式是否更优?若更优,原因是什么?


内容的提问来源于stack exchange,提问作者Ports

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 00:57:28