Hangfire ASP.NET Core MVC [英] Hangfire ASP.NET Core MVC
问题描述
在使用Hangfire(1.6.5)安排/排队MVC动作时遇到麻烦 (自定义IService可以正常工作..)
Having trouble scheduling/enqueuing an MVC action with Hangfire (1.6.5) (Custom IServices works just fine..)
尚未注册"Controllers.MyController"类型的服务.
No service for type 'Controllers.MyController' has been registered.
public class MyController : Controller
{
public IActionResult RenderViewToString()
{
return View();
}
public IActionResult Test()
{
//Attempt 1
Hangfire.BackgroundJob.Enqueue<MyController>(c => c.RenderViewToString());
//Attempt 2
Hangfire.BackgroundJob.Enqueue(() => c.RenderViewToString());
return new EmptyResult();
}
}
推荐答案
默认情况下,未在ASP.NET Core中的依赖项注入系统中注册控制器.您需要显式调用AddControllersAsService
进行注册,如此GitHub问题所述:
By default, controllers aren't being registered with the dependency injection system in ASP.NET Core. You need to explicitly call AddControllersAsService
to register them, as explained in this GitHub issue:
也许我错了,但是当我进行深入测试(并检查Mvc源代码)时,不是从IServiceProvider
解析控制器,而是仅从IServiceProvider
解析了它们的构造函数参数.
Maybe I'm wrong but as I tested deeply (and checked Mvc source code), Controllers are not resolved from IServiceProvider
, but only constructor arguments of them are resolved from IServiceProvider
.
这是设计使然吗?我很惊讶因为,我使用了另一个支持属性注入的DI框架.而且我不能使用属性注入,因为没有从IServiceProvider
请求控制器实例.
Is that by design? I'm very suprised. Because, I'm using a different DI framework which supports property injection. And I can not use property injection since Controller instances are not requested from IServiceProvider
.
您是否在启动中添加了AddControllersAsServices
(
Have you added AddControllersAsServices
in your Startup (https://github.com/aspnet/Mvc/blob/ab76f743f4ee537939b69bdb9f79bfca35398545/test/WebSites/ControllersFromServicesWebSite/Startup.cs#L37)
另请参见有关问题的答案以获取示例和更多详细信息.
See also this answer to a related question for an example and more details.
这篇关于Hangfire ASP.NET Core MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!