从Hangfire backgroundjob C#Web Mvc调用Singleton实例中的方法

时间:2015-08-21 07:56:56

标签: c# asp.net-mvc visual-studio singleton hangfire

正如标题所说,我试图从Hangfire中的backgroundjob调用一个位于Singleton实例中的方法。我尝试使用下面的代码将作业排入队列,但它们都不起作用:

BackgroundJob.Enqueue<MyApplicatonContext>(x => x.TestString());
BackgroundJob.Enqueue(() => MyApplicatonContext.Instance.TestString());

我的单身人士课程如下:

public sealed class MyApplicatonContext 
{
    // Singleton instance
    private readonly static Lazy<MyApplicatonContext> _instance = new Lazy<MyApplicatonContext>(() => new MyApplicatonContext(GlobalHost.ConnectionManager.GetHubContext<MyApplicatonHub>().Clients));

    private readonly string _testString = "It works!";

    private IHubConnectionContext<dynamic> Clients
    {
        get;
        set;
    }

    private MyApplicatonContext (IHubConnectionContext<dynamic> clients)
    {
        Clients = clients;
    }

    public static MyApplicatonContext Instance
    {
        get
        {
            return _instance.Value;
        }
    }

    public string TestString()
    {
        return _testString;
    }
}
然后

Hangfire会生成此作业并出错:

using MyApplicaton.Context;

MyApplicatonContext context = Activate<MyApplicatonContext>(); 
context.TestString();
  

System.InvalidOperationException

     

类型MyApplicaton.Context.MyApplicatonContext不包含方法   签名TestString()

     

System.InvalidOperationException:类型   MyApplicaton.Context.MyApplicatonContext不包含方法   签名TestString() at   Hangfire.Storage.InvocationData.Deserialize()

我怎样才能让它发挥作用?

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

1 个答案:

答案 0 :(得分:0)

我知道这似乎有很多额外的麻烦,但您应该考虑使用IoC容器来管理MyApplicationContext的生命周期,然后加入其中 - 请参阅information on using IoC Containers with hangfire

推动,您可以实现自己的JobActivator课程(同样,说明在IoC Docs中),但我强烈建议您首先调查IoC Container路线。