Hangfire - 没有为此对象定义的无参数构造函数

时间:2017-05-23 16:13:27

标签: c# asp.net hangfire

我正在使用Hangfire来做一些重复工作,但我得到以下例外:

System.MissingMethodException

No parameterless constructor defined for this object.

System.MissingMethodException: No parameterless constructor defined for this object.
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at Hangfire.JobActivator.ActivateJob(Type jobType)
   at Hangfire.JobActivator.SimpleJobActivatorScope.Resolve(Type type)
   at Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext context)
   at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass8_0.<PerformJobWithFilters>b__0()
   at Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter filter, PerformingContext preContext, Func`1 continuation)
   at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass8_1.<PerformJobWithFilters>b__2()
   at Hangfire.Server.BackgroundJobPerformer.PerformJobWithFilters(PerformContext context, IEnumerable`1 filters)
   at Hangfire.Server.BackgroundJobPerformer.Perform(PerformContext context)
   at Hangfire.Server.Worker.PerformJob(BackgroundProcessContext context, IStorageConnection connection, String jobId)

我已经在AppBuilder中初始化了我的Hangfire:

Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage(ConfigurationManager.ConnectionStrings[ConfigurationKeys.DbDefaultConnectionName].ConnectionString);

        app.UseHangfireDashboard();
        app.UseHangfireServer();

基本上,在我的应用程序中,您可以创建合同。每次创建合同时,我都会使用以下行添加新的定期作业:

RecurringJob.AddOrUpdate(() => AutomaticMovementsCreation(contractToCreate.DebitValue, contractId, descriptionId.Result), Cron.Minutely);

这是正在添加RecurringJob的班级的构造者:

public ContractServiceImpl(IAuthService authService, IContractStore contractStore)
{
    _contractStore = contractStore;
    _authService = authService;
}

方法_contractStore正在使用AutomaticMovementsCreation

我认为这是因为依赖注射,但我真的不知道什么是exacly以及如何解决它。顺便说一句,我使用Unity容器来注册我的应用程序依赖项。

整个启动:

public void Configuration(IAppBuilder app)
{
    var httpConfiguration = new HttpConfiguration();

    ConfigureUnity(app, httpConfiguration);
    ConfigureWebApi(httpConfiguration);
    ConfigureAuth(app);

    //Set configuration into Owin
    app.UseWebApi(httpConfiguration);

    Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage(ConfigurationManager.ConnectionStrings[ConfigurationKeys.DbDefaultConnectionName].ConnectionString);

    app.UseHangfireDashboard();
    app.UseHangfireServer();

}

public void ConfigureUnity(IAppBuilder app, HttpConfiguration config) {
    UnityContainer container = UnityConfig.GetConfiguredContainer() as UnityContainer;

    if (app.GetDataProtectionProvider() == null) {
        app.UseAesDataProtectionProvider();
    }

    IDataProtectionProvider dataProtectionProvider = app.GetDataProtectionProvider();

    container.RegisterInstance(dataProtectionProvider);


    app.CreatePerOwinContext(() =>
        UnityConfig.GetConfiguredContainer().Resolve<ApplicationUserManager‌​>()
    );

    config.DependencyResolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());

}

在此方法中GetConfiguredContainer是我注册服务和数据存储的地方。

3 个答案:

答案 0 :(得分:1)

首先,您需要创建UnityContainer的一个实例(在启动时),从web.config加载配置,最后将容器与您的HttpConfiguration相关联。

我不记得代码,但它是这样的:

var container = new UnityContainer(); 
container.LoadConfiguration(); 
config = new HttpConfiguration(); 
config.DependencyResolver = new UnityDependencyResolver(container);
app.UseWebApi(config);   // Something like that

答案 1 :(得分:0)

使用以下代码解决了这个问题:

    Hangfire.GlobalConfiguration.Configuration.UseActivator(new ContainerJobActivator(container));
    Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage(ConfigurationManager.ConnectionStrings[ConfigurationKeys.DbDefaultConnectionName].ConnectionString);
    app.UseHangfireDashboard();
    app.UseHangfireServer();




 public class ContainerJobActivator : JobActivator
    {
        private IUnityContainer _container;

        public ContainerJobActivator(UnityContainer container)
        {
            _container = container;
        }

        public override object ActivateJob(Type type)
        {
            return _container.Resolve(type);
        }
    }

答案 2 :(得分:0)

您需要注入依赖项才能使其正常工作。 安装nuget unity包:

Install-Package Hangfire.Unity

然后在Global.asax上注册你将拥有BootStraper初始化方法。导航到启动strapper类并在初始化中有以下代码,

DependencyResolver.SetResolver(new UnityDependencyResolver(container));

如果您使用Unity,完整代码将类似于以下内容。

public static class Bootstrapper
{
    public static IUnityContainer Initialise()
    {
        var container = BuildUnityContainer();

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

        return container;
     }



 private static IUnityContainer BuildUnityContainer()
 {
    var container = new UnityContainer();       
    GlobalConfiguration.Configuration.UseUnityActivator(container);
    RegisterTypes(container);
    return container;
 }