Asp.net web api与autofac和Hangfire

时间:2015-05-06 23:10:37

标签: autofac owin hangfire

我最近升级到了Hangfire的新版本,我正在尝试使用autofac和Hangfire设置我的webapi。我正在使用Autofac Hangfire集成版本1.1和Hangfire 1.4.2。我正在使用Owin主持。我一直听到以下错误:

  

请求的服务'IFoo'尚未注册。要避免此异常,请注册组件以提供服务,使用IsRegistered()检查服务注册,或使用ResolveOptional()方法解析可选依赖项。

这是我的owin启动配置。我的所有注册都是在AutofacStandardModule类

中完成的
public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        //we will have the firewall block all CE endpoints from the outside instead
        //ConfigureOAuthTokenConsumption(app);

        var storage = new SqlServerStorage("connection string");

        JobStorage.Current = storage;

        app.UseHangfireServer(new BackgroundJobServerOptions(),storage);
        app.UseHangfireDashboard("/Hangfire",new DashboardOptions(),storage);
        var builder = new ContainerBuilder();
        builder.RegisterModule(new AutofacStandardModule()); 
        var container = builder.Build();

        GlobalConfiguration.Configuration.UseAutofacActivator(container);
        }
}

另外,这是我的web api配置类。我不知道我应该如何在这里配置Hangfire ..

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config, Autofac.Module moduleToAppend)
    {
        config.MapHttpAttributeRoutes();

        config.EnableCors();
        config.EnableSystemDiagnosticsTracing();

        var builder = new ContainerBuilder(); 

        builder.RegisterAssemblyTypes(
            Assembly.GetExecutingAssembly())
                .Where(t =>
                    !t.IsAbstract && typeof(ApiController).IsAssignableFrom(t))
                .InstancePerLifetimeScope();

        builder.RegisterModule(
            new AutofacStandardModule()); 

        if (moduleToAppend != null)
        {
            builder.RegisterModule(moduleToAppend);
        }

        var container = builder.Build();

        config.DependencyResolver = new AutofacWebApiDependencyResolver(
            container);

        //Hangfire.GlobalConfiguration.Configuration.UseAutofacActivator(container);

        //JobActivator.Current = new AutofacJobActivator(container);
        }
}

1 个答案:

答案 0 :(得分:1)

我解决了这个问题,似乎我没有明确说明我的工作在入队时是哪种类型。

做了什么是改变

_jobClient.Enqueue(
            () => _foo.Bar(fooId, fooId2));

.. ..成

_jobClient.Enqueue<IFoo>(x => x.Bar(fooId, fooId2));