Having trouble scheduling/enqueuing an MVC action with Hangfire (1.6.5)
(Custom IServices works just fine..)
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();
}
}
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:
Hi,
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
.
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
.
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.