.net core 中在定时器中获取数据上下文

最近在通过微软官方教程学习使用.netCore搭建后台,在尝试使用token时遇到了问题。

我使用

services.AddDbContext<TokenContext>(opt => opt.UseInMemoryDatabase("Token"));

这个方法建立了token的表,在Controller类中可以通过构造函数依赖注入获取到其单例。

但是当我尝试使用定时器进行token的过期管理时,我发现我无法获取到token表这个对象。

我使用了继承了BackgroundService这个类的托管服务类进行定时操作,当我尝试使用和Controller相同的依赖注入方法获取时,运行时报了以下异常。

System.AggregateException:“Some services are not able to be constructed 

当我使用

ServiceLocator.Instance.GetService<TokenContext>();

这个方法时,运行时报了以下异常

Cannot resolve scoped service 'ModelMasterService.Models.TokenContext' from root provider.

请问有什么方法可以获取到这个对象么?亦或者是我使用的方法从一开始就不对么?

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 以帮助更多的人 ^-^