![](/img/trans.png)
[英]ASP.NET Core Dependency Injection error - Unable to resolve service for type “Repository” while attempting to activate “Service”
[英].NET Core Dependency Injection; Unable to resolve service for type 'System.String' while attempting to activate Service
我有一个服务和一个模型来获取其构造函数的参数,然后控制器使用该服务。 我也使用依赖注入,我不能完全指出如何声明服务,因为它需要一个参数。 我已经研究了另一个类似的问题,但似乎没有一个答案对我有用。 我得到的错误是:“在尝试激活 'authentication.Services.RDStationServices.RDStationService' 时,无法解析类型为 'System.String' 的服务。
与此事相关的代码:
public class RDStationService : IRDStationService
{
public RDStationService(string server)
{
_endPoint = server;
_client = new RestClient
{
BaseUrl = new Uri(_endPoint)
};
}
}
模型:
public class RDStationOptions
{
public string Url { get; set; }
}
环境变量:
"RDStationOptions": {
"Url": "https://www.rdstation.com.br/api/1.3/"}
启动:
public void ConfigureServices(IServiceCollection services)
{
var configOptionsRDStation = Configuration.GetSection(nameof(RDStationOptions));
var _rdStationInstance = new RDStationService(configOptionsRDStation[nameof(RDStationOptions.Url)]);
services.AddSingleton(_rdStationInstance);
}
ConfigureServices 中的此配置是我将字符串通知给构造函数的最新尝试,但我不断收到相同的错误。 请问有什么建议吗?
由于您使用 ASP.NET Core,我假设您的Configuration
实例是IConfiguration
类型。 这应该适合你:
public void ConfigureServices(IServiceCollection services)
{
var configOptionsRDStation = Configuration.GetSection("RDStationOptions : Url");
var _rdStationInstance = new RDStationService(configOptionsRDStation.Value);
services.AddSingleton(_rdStationInstance);
}
如果你想使用IOptions
:
services.Configure<RDStationOptions>(Configuration.GetSection("RDStationOptions"));
services.AddOptions()
您发布的代码按预期工作。 我觉得你的错误是由其他代码引起的。 也许发布您的其余配置。
我希望这种情况发生的地方的一个例子:
services.AddSingleton(_rdStationInstance);
// Will NOT work, will created a scoped RDStationService and try to resolve string
services.AddScoped<IRDStationService, RDStationService>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.