![](/img/trans.png)
[英]Net Core 2 Console App - DI 'Unable to resolve service for type…'
[英].net core bot DI error Unable to resolve service
我正在嘗試按照Microsoft的文檔將LUIS添加到我的機器人中,因此我創建了BotServices
類,並在Startup.cs
BotServices
其添加到我的服務集合中
var connectedServices = new BotServices(botConfig);
services.AddSingleton<BotServices>(sp => connectedServices);
然后將其注入MyBot
類中
public MyBot(BotServices botServices)
但是我得到這個錯誤
System.InvalidOperationException: Unable to resolve service for type 'BotServices' while attempting to activate 'MyBot'. at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
在自己實例化對象時,您嘗試執行以下操作:
var connectedServices = new BotServices(botConfig);
services.AddSingleton<BotServices>(connectedServices);
即不需要您現在擁有的工廠lambda(它正在獲取指向您的實例的局部變量...可能會導致問題...
我的代碼的問題是我在這樣的services.AddBot<IBot>
調用中注冊了BotServices
沒用:
services.AddBot<MyBot>(options =>
{
var botConfig = BotConfiguration.Load(botFilePath ?? @".\MyBot.bot", secretKey);
services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded. ({botConfig})"));
var connectedServices = new BotServices(botConfig);
services.AddSingleton<BotServices>(sp => connectedServices);
}
我這樣做是因為在使用空的bot模板創建時,默認情況下在其中定義了'botConfig'變量,因此我將其移出並可以使用! (但我仍然無法解釋為什么它不起作用)
作品
var botConfig = BotConfiguration.Load(botFilePath ?? @".\MyBot.bot", secretKey);
services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded. ({botConfig})"));
var connectedServices = new BotServices(botConfig);
services.AddSingleton<BotServices>(sp => connectedServices);
services.AddBot<MyBot>(options =>
{
//all the bot configuration code
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.