【发布时间】:2019-10-28 04:04:07
【问题描述】:
在 .net core 2 中,我创建了一个托管服务,其自定义属性如下:
public class MyService : BackgroundService
{
public bool IsRunning {get;set;}
...
我可以在 startup.cs 中设置如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHostedService,HostedServices.MyService>();
...
然后我可以在剃须刀页面的其他地方引用它,例如:
public class IndexModel : PageModel
{
private readonly IHostedService _mySrv;
public IndexModel(IHostedService mySrv) => _mySrv = mySrv;
[BindProperty]
public bool IsRunning { get; set; }
public void OnGet() => IsRunning = ((HostedServices.MyService)_mySrv).IsRunning;
}
现在我已升级到 .net core 3,我的启动已更改为:
services.AddHostedService<HostedServices.MyService>();
但是我在 IndexModel 中的 DI 引用不再获得我的 MyService,而是给了我一个 GenericWebHostService 类型的对象,我不知道如何从中获得我的自定义 MyService。在 IndexModel 中将“IHostedService”更改为“MyService”也不起作用,我收到“无法解析服务”错误。
如何从依赖注入中获取 MyService 的实例?
【问题讨论】:
标签: c# asp.net-core asp.net-core-3.0 asp.net-core-hosted-services