Hangfire dependency injection with .net core

后端 未结 8 1912
孤城傲影
孤城傲影 2020-12-08 02:02

How can I use .net core\'s default dependency injection in Hangfire ?

I am new to Hangfire and searching for an example which works with asp.net core.

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 02:27

    All of the answers in this thread are wrong/incomplete/outdated. Here's an example with ASP.NET Core 3.1 and Hangfire.AspnetCore 1.7.

    Client:

    //...
    using Hangfire;
    // ...
    
    public class Startup
    {
        // ...
    
        public void ConfigureServices(IServiceCollection services)
        {
            //...
            services.AddHangfire(config =>
            {
                // configure hangfire per your requirements
            });
        }
    }
    
    public class SomeController : ControllerBase
    {
        private readonly IBackgroundJobClient _backgroundJobClient;
    
        public SomeController(IBackgroundJobClient backgroundJobClient)
        {
            _backgroundJobClient = backgroundJobClient;
        }
        
        [HttpPost("some-route")]
        public IActionResult Schedule([FromBody] SomeModel model)
        {
            _backgroundJobClient.Schedule(s => s.Execute(model));
        }
    }
    

    Server (same or different application):

    {
        //...
        services.AddScoped();
    
        services.AddHangfire(hangfireConfiguration =>
        {
            // configure hangfire with the same backing storage as your client
        });
        services.AddHangfireServer();
    }
    
    public interface ISomeDependency { }
    public class SomeDependency : ISomeDependency { }
    
    public class SomeClass
    {
        private readonly ISomeDependency _someDependency;
    
        public SomeClass(ISomeDependency someDependency)
        {
            _someDependency = someDependency;
        }
    
        // the function scheduled in SomeController
        public void Execute(SomeModel someModel)
        {
    
        }
    }
    

提交回复
热议问题