网站首页 文章专栏 实现类具有多个构造函数,依赖注入的处理办法
实现类具有多个构造函数,依赖注入的处理办法
发布 作者:被打断de狗腿 浏览量:613
多个构造函数依赖注入处理办法

我的SteamGameService实现类有两个构造函数,一个有DpOption数据库配置的参数,一个没有,用于单元测试

public class SteamGameService : BasicService<SteamGame>, ISteamGameService
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _configuration;
    private readonly ILogger<SteamGameService> _logger;

    public SteamGameService(
        HttpClient httpClient,
        IConfiguration configuration,
        ILogger<SteamGameService> logger)
    {
        _httpClient = httpClient;
        _configuration = configuration;
        _logger = logger;
    }

    public SteamGameService(
        DbOption dbOption,
        HttpClient httpClient,
        IConfiguration configuration,
        ILogger<SteamGameService> logger) : base(dbOption)
    {
        _httpClient = httpClient;
        _configuration = configuration;
        _logger = logger;
    }

    // todo ...
}

这里可以使用ActivatorUtilitiesConstructorAttribute特性来标注希望DI使用的构造函数

像这样,[ActivatorUtilitiesConstructor] ctor(parameter)。 然后需要使用ActivatorUtilities类来创建实例

services.AddHttpClient<ISteamGameService, SteamGameService>((sp,client) =>
{
    ActivatorUtilities.CreateInstance<SteamGameService>(sp);
    client.BaseAddress = new Uri("https://api.steampowered.com");
});
loading