gpt4 book ai didi

asp.net-core - Blazor:如何获取托管服务实例?

转载 作者:行者123 更新时间:2023-12-05 01:39:29 25 4
gpt4 key购买 nike

我添加了一个周期性做某事的后台服务,就像官方示例一样。

public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddHostedService<TimedHostedService>(); <-- here
services.AddSingleton<WeatherForecastService>();
}

TimedHostedServiceStartAsyncStopAsync。最终,我想在网络浏览器中调用它们。

在默认脚手架的 FetchData.razor 文件中,我尝试直接引用该服务,但没有成功。因此,我向 WeatherForecastService 添加了 StartStop 方法,并在点击事件时调用它们。

<button @onclick="()=> { ForecastService.Stop(); }">Stop</button>

现在的问题是,我不知道如何在 WeatherForecastServiceStop 方法中获取 TimedHostedService 的运行实例.

public class WeatherForecastService
{
....
public void Stop()
{
//how to get TimedHostedService instance?
}
....
}

我曾尝试使用依赖注入(inject)来获取服务提供者,但 GetService 返回 null。

IServiceProvider sp;
public WeatherForecastService(IServiceProvider sp)
{
this.sp = sp;
}

public void Stop()
{
var ts = sp.GetService(typeof(TimedHostedService)) as TimedHostedService;
ts.StopAsync(new CancellationToken());
}

最佳答案

我质疑从 GUI 操作服务是否明智,但如果您确定需要这个,那么它就是关于如何注册该服务的问题。

启动时:

services.AddSingleton<TimedHostedService>();
services.AddHostedService(sp => sp.GetRequiredService<TimedHostedService>());

然后你就可以

@inject TimedHostedService TimedService

关于asp.net-core - Blazor:如何获取托管服务实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58250893/

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