【发布时间】:2018-10-27 21:53:24
【问题描述】:
在 ASP.NET Core 2.0 中,有一种方法可以通过实现IHostedService 接口来添加后台任务(请参阅https://docs.microsoft.com/en-us/aspnet/core/fundamentals/hosted-services?view=aspnetcore-2.0)。按照本教程,我能够让它工作的方法是在 ASP.NET Core 容器中注册它。我的目标是从队列中读取消息并在后台处理作业;一条消息被发布到队列(通过控制器操作),然后在后台按时间间隔进行处理。
// Not registered in SimpleInjector
services.AddSingleton<IHostedService, MyTimedService>();
当我将此注册放入 ASP.NET Core 容器中时,它会在应用程序启动时自动启动该过程。但是,当我在 SimpleInjector 中注册它时,该服务不会自动启动。我相信是这样的,因为我们只用 MvcControllers 和 MvcViewComponents 注册了 SimpleInjector 容器:
// Wire up simple injector to the MVC components
container.RegisterMvcControllers(app);
container.RegisterMvcViewComponents(app);
我遇到的问题是当我想开始将组件注册从 SimpleInjector(例如存储库、带有装饰器的通用处理程序...)注入到 IHostedService 的实现中,如下所示:
public class TimedService : IHostedService, IDisposable
{
private IJobRepository _repo;
private Timer _timer;
public TimedService(IJobRepository repo)
{
this._repo = repo;
}
...
...
...
}
由于IHostedService 注册到 ASP.NET Core 而不是 Simple Injector,所以在运行定时后台服务时收到以下错误:
未处理的异常:System.InvalidOperationException:尝试激活“Optimization.API.BackgroundServices.TimedService”时无法解析“Optimization.Core.Interfaces.IJobRepository”类型的服务。
所以我的问题是,在 Simple Injector 中实现后台任务的最佳方式是什么?与标准 MVC 集成相比,这是否需要单独的集成包?如何将我的 Simple Injector 注册注入 IHostedService?如果我们在 Simple Injector 中注册后能自动启动服务,我想就可以解决这个问题了。
感谢您在此处提供的任何指示以及有关此主题的任何建议!我可能做错了什么。在过去的一年里,我非常喜欢使用 Simple Injector。
【问题讨论】:
标签: c# dependency-injection asp.net-core-2.0 simple-injector