在WebApi中使用Autofac进行Hangfire

时间:2016-02-21 10:17:31

标签: c# asp.net-web-api autofac hangfire hangfire-autofac

我在startup.cs中有以下配置,但我收到错误,虽然我已经安装了Hangifre.Autofac nuget包并进行了配置。

  

从中可以看到没有与“AutofacWebRequest”匹配的标记的范围   请求实例的范围。这通常表明   正在请求按照HTTP请求注册的组件   一个SingleInstance()组件(或类似的场景。)在网络下   集成始终请求来自的依赖项   DependencyResolver.Current或ILifetimeScopeProvider.RequestLifetime,   从来没有从容器本身。

Startup.cs

 public void Configuration(IAppBuilder app)
        {

            var builder = new ContainerBuilder();


            //if (AppConfigHelper.PlatformEnvironment == PlatformEnvironment.LocalHost)
            builder.RegisterType<NLogLogger>().As<ILogger>().InstancePerLifetimeScope();
            //else
            //builder.RegisterType<SentryLogger>().As<ILogger>().InstancePerLifetimeScope();

            //builder.RegisterWebApiFilterProvider(configuration);

            // REGISTER CONTROLLERS SO DEPENDENCIES ARE CONSTRUCTOR INJECTED
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();

            //These lines warm up dlls and load into memory for automatic regisration
            var r = new ReplyRepository(null);
            var s = new BankService();

            builder.RegisterModule(new SelfRegisterModule());
            builder.RegisterModule(new RepositoryModule());
            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new EFModule());


            builder
                   .RegisterType<ApplicationOAuthProvider>()
                   .As<IOAuthAuthorizationServerProvider>()
                   .PropertiesAutowired() // to automatically resolve IUserService
                   .SingleInstance(); // you only need one instance of this provider

            builder.RegisterType<SellutionUserStore>().As<IUserStore<ApplicationUser, int>>().InstancePerBackgroundJob().InstancePerRequest();
            builder.RegisterType<SellutionUserManager>().AsSelf().InstancePerBackgroundJob().InstancePerRequest();
            builder.RegisterType<SellutionRoleManager>().AsSelf().InstancePerBackgroundJob().InstancePerRequest();
            builder.RegisterType<SellutionSignInManager>().AsSelf().InstancePerBackgroundJob().InstancePerRequest();
            builder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerBackgroundJob().InstancePerRequest();
            builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerBackgroundJob().InstancePerRequest();

            builder.RegisterType<TicketDataFormat>().As<ISecureDataFormat<AuthenticationTicket>>();

            builder.RegisterType<TicketSerializer>().As<IDataSerializer<AuthenticationTicket>>();
            builder.Register(c => new DpapiDataProtectionProvider("Sellution360").Create("ASP.NET Identity")).As<IDataProtector>();

            builder.RegisterType<CurrencyRatesJob>().AsSelf().InstancePerBackgroundJob();

            // BUILD THE CONTAINER
            var container = builder.Build();

            Hangfire.GlobalConfiguration.Configuration.UseAutofacActivator(container);
            JobActivator.Current = new AutofacJobActivator(container);


            // REPLACE THE MVC DEPENDENCY RESOLVER WITH AUTOFAC
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Set the dependency resolver for Web API.
            var webApiResolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

            // Set the dependency resolver for MVC.
            var mvcResolver = new AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(mvcResolver);


            // Register the Autofac middleware FIRST, then the Autofac MVC middleware.
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc().UseCors(CorsOptions.AllowAll);
            app.UseAutofacWebApi(GlobalConfiguration.Configuration).UseCors(CorsOptions.AllowAll); ;

            IocManager.Instance.IocContainer = container;

            ConfigureAuth(app);
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();

            Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("DefaultConnection");
            app.UseHangfireDashboard();
            app.UseHangfireServer();

            RecurringJob.AddOrUpdate<CurrencyRatesJob>(j => j.Execute(), Cron.Minutely);
        }

CurrencyRatesJob.cs

 public class CurrencyRatesJob
    {
        private readonly ILogger _logger;
        private readonly IBusinessTypeService _businessTypeService;

        public CurrencyRatesJob(ILogger logger, IBusinessTypeService businessTypeService)
        {
            _logger = logger;
            _businessTypeService = businessTypeService;
        }

        public void Execute()
        {
            var types = _businessTypeService.GetBusinessTypes();
            _logger.Log("waqar");

        }
    }

1 个答案:

答案 0 :(得分:1)

InstancePerBackgroundJob使用Per Macthing Life Time标记创建BackgroundJobScope范围。但Per Request个实例在另一个带Request标记的生命周期内得到解决。因此,当您在Per Request生命周期内尝试解析BackgroundJobScope对象时,会出错。它说,你只能在Request生命周期内解决我,而不是在root或其他生活中。因此,您应该使用Per Life Time Scope代替Per Request

所以这些Per Life Time Scope注册的对象将获得父母的生命望远镜。如果它是单身人士,他们将在根。如果他们的父生命望远镜是请求,他们将与此请求范围一起生活。 InstancePerBackgroundJob它们将在BackgroundJobScope生命周期范围内生效。

如果背景对象使用请求生命周期范围,则可以在请求完成时处理对象,这对后台对象有好处。此外,如果他们在根范围内,他们将永远不会处置。