Hangfire dependency injection with .net core

后端 未结 8 1905
孤城傲影
孤城傲影 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:12

    As far as I am aware, you can use .net cores dependency injection the same as you would for any other service.

    You can use a service which contains the jobs to be executed, which can be executed like so

    var jobId = BackgroundJob.Enqueue(x => x.SomeTask(passParamIfYouWish));

    Here is an example of the Job Service class

    public class JobService : IJobService
    {
        private IClientService _clientService;
        private INodeServices _nodeServices;
    
        //Constructor
        public JobService(IClientService clientService, INodeServices nodeServices)
        {
            _clientService = clientService;
            _nodeServices = nodeServices;
        }
    
        //Some task to execute
        public async Task SomeTask(Guid subject)
        {
            // Do some job here
            Client client = _clientService.FindUserBySubject(subject);
        }      
    }
    

    And in your projects Startup.cs you can add a dependency as normal

    services.AddTransient< IClientService, ClientService>();

    Not sure this answers your question or not

提交回复
热议问题