小编zhi*_*iyw的帖子

如何访问用AddSingleton<T>注入的后台服务成员

在asp.netcore web api项目中,有一个名为TimedHostedService的后台服务,通过AddSingleton<>注入,当从控制器访问该服务的成员[ ExecutionCount ]时,该值始终等于0,当设置成员[ ExecutionCount ]时改为static,值就变了,不知道为什么?属性 [ ExecutionCount ] 必须是静态的吗?

\n

定时托管服务:

\n
public class TimedHostedService : IHostedService, IDisposable\n{\n    private int executionCount = 0;\n    private readonly ILogger<TimedHostedService> _logger;\n    private Timer _timer;\n\n    public int ExecutionCount\n    {\n        get { return executionCount; }\n        set { executionCount = value; }\n    }\n\n    public TimedHostedService(ILogger<TimedHostedService> logger)\n    {\n        _logger = logger;\n    }\n\n    public Task StartAsync(CancellationToken stoppingToken)\n    {\n        _logger.LogInformation("Timed Hosted Service running.");\n\n        _timer = new Timer(DoWork, null, TimeSpan.Zero,\n            TimeSpan.FromSeconds(1));\n\n        return Task.CompletedTask;\n    }\n\n    private void DoWork(object state)\n    {\n …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection asp.net-core

2
推荐指数
1
解决办法
1282
查看次数

标签 统计

asp.net-core ×1

c# ×1

dependency-injection ×1