尝试激活'我的服务'时,无法解析'系统字符串'类型的服务我的、字符串、类型、系统

2023-09-03 10:40:39 作者:听风说爱你

我在我的服务结构无状态ASP.NET核心应用程序中看到以下异常。

System.InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate 'MyService'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.CreateCallSite(ServiceProvider provider, ISet`1 callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetResolveCallSite(IService service, ISet`1 callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetServiceCallSite(Type serviceType, ISet`1 callSiteChain)
怎么可能无法解析System.String?我如何进一步调试它?

推荐答案

ASP.NET Core中的默认DI框架在可用功能方面受到限制。 假定类构造函数类似于

public MyService(string dependencyString) {
    //...
}
win7为什么我激活了,但是右键电脑查看属性时显示的未激活 求解

容器无法知道要将依赖字符串注入到服务中要使用什么值。

在上述情况下,可以在将服务添加到集合时使用其中一个重载提供缺少的string

//...

services.AddScoped<IMyService>(_ => new MyService("value here"));

//...

这样在激活服务时可以正确地返回它。

文档参考:Dependency injection in ASP.NET Core->;Constructor injection behavior (v2.1)