Using IoC containers¶
As I said in the previous section Hangfire uses the JobActivator
class to instantiate the target types before invoking instance methods. You can override its behavior to perform more complex logic on a type instantiation. For example, you can tell it to use IoC container that is used in your project:
- public class ContainerJobActivator : JobActivator
- {
- private IContainer _container;
- public ContainerJobActivator(IContainer container)
- {
- _container = container;
- }
- public override object ActivateJob(Type type)
- {
- return _container.Resolve(type);
- }
- }
Then, you need to register it as a current job activator before starting the Hangfire server:
- // Somewhere in bootstrap logic, for example in the Global.asax.cs file
- var container = new Container();
- GlobalConfiguration.Configuration.UseActivator(new ContainerJobActivator(container));
- ...
- app.UseHangfireServer();
To simplify the initial installation, there are some integration packages already available on NuGet. Please see the Extensions page on the official site to get the list of all available extension packages: https://www.hangfire.io/extensions.html#ioc-containers.
Some of these activators also provide an extension method for the GlobalConfiguration
class:
- GlobalConfiguration.Configuration.UseNinjectActivator(kernel);
HttpContext
is not available
Request information is not available during the instantiation of a target type. If you register your dependencies in a request scope (InstancePerHttpRequest
in Autofac, InRequestScope
in Ninject and so on), an exception will be thrown during the job activation process.
So, the entire dependency graph should be available. Either register additional services without using the request scope, or use separate instance of container if your IoC container does not support dependency registrations for multiple scopes.
原文:
http://docs.hangfire.io/en/latest/background-methods/using-ioc-containers.html