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

.NET Core依赖注入报错:激活Factory时无法解析System.String类型

问题原因

.NET 内置依赖注入容器激活服务时,会自动尝试解析构造函数中声明的所有参数。你的Factory构造函数包含string sample参数,但容器中没有对应可解析的字符串值配置,因此抛出Unable to resolve service for type 'System.String' while attempting to activate 'Factory'错误。

注意:不要尝试全局注册System.String类型的实例,这会导致所有需要字符串参数的服务都被注入该值,极易引发其他依赖解析异常。

可行解决方案

方案1:注册服务时手动传入字符串参数(实现成本最低)

注册Factory时不使用容器自动构造的逻辑,通过工厂委托手动创建实例,自行传入字符串参数取值:

// 先注册Factory依赖的A类型
builder.Services.AddScoped<A>();

// 读取需要传入的字符串值,比如从配置文件读取
var sampleVal = builder.Configuration.GetValue<string>("FactorySamplePath") ?? string.Empty;

// 注册IFactory实现
builder.Services.AddScoped<IFactory, Factory>(serviceProvider =>
{
    // 从容器中获取已注册的A实例
    var aInstance = serviceProvider.GetRequiredService<A>();
    // 手动传入字符串参数构造Factory实例
    return new Factory(aInstance, sampleVal);
});

方案2:使用强类型配置封装参数(符合DI最佳实践)

原生字符串参数没有类型标识,很容易和其他字符串依赖混淆,推荐将配置封装为强类型选项类,从根本上避免参数匹配错误。

  1. 首先定义对应配置类:
public class FactoryOptions
{
    public string SamplePath { get; set; } = string.Empty;
}
  1. 修改Factory构造函数,注入选项类而非裸字符串:
public class Factory : IFactory
{
    private readonly A _a;
    private readonly string _test;

    public Factory(A a, IOptions<FactoryOptions> options)
    {
        _a = a;
        var sample = options.Value.SamplePath;
        _test = string.IsNullOrEmpty(sample) ? string.Empty : Path.GetFullPath(sample);
    }

    private string Create(long id)
    {
        var b = _test.make(id);
        return b;
    }
}
  1. 在Program.cs中绑定配置并注册服务:
builder.Services.AddScoped<A>();
// 将配置文件中对应节点绑定到FactoryOptions
builder.Services.Configure<FactoryOptions>(builder.Configuration.GetSection("FactorySettings"));
// 正常注册Factory即可,容器可自动解析IOptions<FactoryOptions>参数
builder.Services.AddScoped<IFactory, Factory>();

你可以在appsettings.json中添加对应配置节点传值:

{
  "FactorySettings": {
    "SamplePath": "your/target/path/value"
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 18:51:20