Hangfire ASP.NET Core MVC

2019-09-07 01:46发布

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();
    }
}

1条回答
地球回转人心会变
2楼-- · 2019-09-07 01:48

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.

查看更多
登录 后发表回答