Hangfire server unable to pick job in case of strategy design pattern

做~自己de王妃 提交于 2019-11-29 11:47:20

The answer is right there in the exception

No parameterless constructor defined for this object.

Your OperationStrategy doesn't have a parameterless constructor, so when Hangfire tries to create this object, it can't - it does so through reflection. Hangfire does not have access to the instance that you used when scheduling the job, it attempts to recreate it. Which it can't do.

You could add a parameterless constructor, and make Operations a public collection.

This will enable you to use your ctor exactly as you currently are, but also allow the object to be serialized, stored by Hangfire, then deserialized and created when it tries to run.

public class OperationStrategy : IOperationStrategy
{
    // paramaterless ctor
    public OperationStrategy()
    {
        Operations = new List<Operation>(); 
    }

    public OperationStrategy(params IOperation[] operations)
    {
        if (operations == null)
            throw new ArgumentNullException(nameof(operations));

        Operations = operations;
    }

    public Output Process(Type type, Input input)
    {
        var op = Operations.FirstOrDefault(o => o.AppliesTo(type));

        if (op == null)
            throw new InvalidOperationException($"{operation} not registered.");

        return op.Process(input);
    }

    //property - this can be deserialized by Hangfire
    public List<IOperation> Operations {get; set;}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!