c# - Hangfire RecurringJob with dependency injection -
is possible have hangfire instantiate objects configure jobactivator when they're scheduled run recurringjob?
the signature of method seems force static usages:
public static void addorupdate<t>( string recurringjobid, expression<action<t>> methodcall,
i have several ideas on how "abuse" statics channel things around, feel might missing something. there design decision hangfire supports statics in chron jobs?
quick answer no, default job activator works on parameter-less constructors or static methods. did (in vb.net) quick , dirty see if working , have shown below.
by using "addorupdate", telling hangfire create instance of t , access method of t, signature works on instance members, not statics. if use 1 of other "addorupdate" method signatures without generic parameter, require static.
now fun part: if type t doesn't have parameter-less default constructor fail using default jobactivator said.
this can use custom jobactivator supply dependencies constructors of tasks. if create own class inheriting jobactivator can supply dependencies jobs.
here vb code:
imports hangfire imports system.reflection public class jobactivationcontainer inherits jobactivator private property parametermap dictionary(of type, [delegate]) private function compareparametertomap(p parameterinfo) boolean dim result = parametermap.containskey(p.parametertype) return result end function public overrides function activatejob(jobtype type) object dim candidatector reflection.constructorinfo = nothing 'loop through ctor's , find specific ctor map has types. jobtype. getconstructors. tolist. foreach( sub(i) if i.getparameters.tolist. trueforall(addressof compareparametertomap) if candidatector nothing candidatector = if isnot candidatector andalso i.getparameters.count > candidatector.getparameters.count candidatector = end if end sub ) if candidatector nothing 'if ctor null, use default activator. return mybase.activatejob(jobtype) else 'create list of parameters in order , activate dim ctorparameters new list(of object) candidatector.getparameters.tolist.foreach(sub(i) ctorparameters.add(parametermap(i.parametertype).dynamicinvoke())) return activator.createinstance(jobtype, ctorparameters.toarray) end if end function public sub registerdependency(of t)(factory func(of t)) if not parametermap.containskey(gettype(t)) parametermap.add(gettype(t), factory) end sub public sub new() parametermap = new dictionary(of type, [delegate]) end sub end class
i know doesn't answer question on how "abuse" statics, show how roll-your-own ioc container hangfire, or use 1 of supported ioc's per manual: http://hangfirechinese.readthedocs.org/en/latest/background-methods/using-ioc-containers.html
note: plan use proper ioc, code above purely academic , need lot of work!
Comments
Post a Comment