gpt4 book ai didi

azure - 抛出异常 : 'System.InvalidOperationException' in Microsoft. Extensions.DependencyInjection

转载 作者:行者123 更新时间:2023-12-03 04:11:51 26 4
gpt4 key购买 nike

我正在使用 ASP.NET Core 进行网络作业。我无法正确设置依赖注入(inject)。

public static async Task Main(string[] args)
{
var host = BuildHost(args);

using (host)
{
await host.RunAsync();
}
}


public static IHost BuildHost(string[] args) =>
new HostBuilder()
.ConfigureHostConfiguration(builder =>
{
builder
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
})
.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddAzureStorage();
b.AddTimers();
})
.ConfigureServices((hostBuilderContext, services) =>
{
services.AddScoped<ISchedularService, SchedularService>();
//services.AddSingleton<IHostedService, PrintTimeService>()
}).Build();

在functions.cs文件中,我在构造函数中访问了调度程序服务。但它没有触发构造函数并抛出异常,例如:

Exception thrown: 'System.InvalidOperationException' in Microsoft.Extensions.DependencyInjection

public class Functions
{

private readonly ISchedularService _schedularService;
public Functions(SchedularService schedularService)
{
_schedularService = schedularService;
}
}

最佳答案

请确保您使用的是最新的软件包。我将你的代码与最新的软件包一起使用,效果很好。

我没有使用异步方法。

       static void Main(string[] args)
{

var host = BuildHost(args);

using (host)
{
host.Run();
}
}

public static IHost BuildHost(string[] args) =>
new HostBuilder()
.ConfigureHostConfiguration(builder =>
{
builder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
})
.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddAzureStorage();
b.AddTimers();
})
.ConfigureServices((hostBuilderContext, services) =>
{
services.AddScoped<IWebJobConfiguration,WebJobConfiguration>();
})
.Build();

在 Functions.cs 中:

        private readonly IWebJobConfiguration _webJobConfiguration;
public Functions(IWebJobConfiguration webJobConfiguration)
{
Console.WriteLine("*** DI via constructor ***");
_webJobConfiguration = webJobConfiguration;
}

public void ProcessQueueMessage([QueueTrigger("queue111")] string message, ILogger logger)
{
Console.WriteLine(_webJobConfiguration.Message);
Console.WriteLine(message + ";consoleqqqq");
}

结果:

enter image description here

关于azure - 抛出异常 : 'System.InvalidOperationException' in Microsoft. Extensions.DependencyInjection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56057124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com