Passing dependencies¶

In almost every job you’ll want to use other classes of your application to perform different work and keep your code clean and simple. Let’s call these classes as dependencies. How to pass these dependencies to methods that will be called in background?

When you are calling static methods in background, you are restricted only to the static context of your application, and this requires you to use the following patterns of obtaining dependencies:

  • Manual dependency instantiation through the new operator
  • Service location
  • Abstract factories or builders
  • Singletons
    However, all of these patterns greatly complicate the unit testability aspect of your application. To fight with this issue, Hangfire allows you to call instance methods in background. Consider you have the following class that uses some kind of DbContext to access the database, and EmailService to send emails.
  1. public class EmailSender
  2. {
  3. public void Send(int userId, string message)
  4. {
  5. var dbContext = new DbContext();
  6. var emailService = new EmailService();
  7.  
  8. // Some processing logic
  9. }
  10. }

To call the Send method in background, use the following override of the Enqueue method (other methods of BackgroundJob class provide such overloads as well):

  1. BackgroundJob.Enqueue<EmailSender>(x => x.Send(13, "Hello!"));

When a worker determines that it need to call an instance method, it creates the instance of a given class first using the current JobActivator class instance. By default, it uses the Activator.CreateInstance method that can create an instance of your class using its default constructor, so let’s add it:

  1. public class EmailSender
  2. {
  3. private IDbContext _dbContext;
  4. private IEmailService _emailService;
  5.  
  6. public EmailSender()
  7. {
  8. _dbContext = new DbContext();
  9. _emailService = new EmailService();
  10. }
  11.  
  12. // ...
  13. }

If you want the class to be ready for unit testing, consider to add constructor overload, because the default activator can not create instance of class that has no default constructor:

  1. public class EmailSender
  2. {
  3. // ...
  4.  
  5. public EmailSender()
  6. : this(new DbContext(), new EmailService())
  7. {
  8. }
  9.  
  10. internal EmailSender(IDbContext dbContext, IEmailService emailService)
  11. {
  12. _dbContext = dbContext;
  13. _emailService = emailService;
  14. }
  15. }

If you are using IoC containers, such as Autofac, Ninject, SimpleInjector and so on, you can remove the default constructor. To learn how to do this, proceed to the next section.

原文:

http://docs.hangfire.io/en/latest/background-methods/passing-dependencies.html