尝试激活'我的服务'时,无法解析'系统字符串'类型的服务 [英] Unable to resolve service for type 'System.String' while attempting to activate 'MyService'

查看:0
本文介绍了尝试激活'我的服务'时,无法解析'系统字符串'类型的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的服务结构无状态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) {
    //...
}

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

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

//...

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

//...

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


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

这篇关于尝试激活&#39;我的服务&#39;时,无法解析&#39;系统字符串&#39;类型的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆