Hangfire With Autofac in WebApi

本文关键字:WebApi in Autofac With Hangfire | 更新日期: 2023-09-27 18:35:36

我在启动时有以下配置.cs但是尽管我已经安装了nuget包并进行了配置Hangifre.Autofac但我还是遇到了错误。

请求实例的范围。这通常表明 注册为每 HTTP 请求的组件正在由 SingleInstance() 组件(或类似方案)。在网络下 集成始终从 DependencyResolver.Current 或 ILifetimeScopeProvider.RequestLifetime, 永远不要来自容器本身。

启动.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);
        }

货币汇率工作.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");
        }
    }

Hangfire With Autofac in WebApi

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

因此,这些Per Life Time Scope注册的对象将获得父对象的生命周期范围。如果是单例,它们将处于根中。如果他们的父生存期范围是请求,他们将使用此请求范围。对于InstancePerBackgroundJob他们来说是一样的,他们将生活在BackgroundJobScope生命周期范围内。

如果

后台对象使用请求生存期范围,则可以在请求完成时释放对象,则具有另一个生命周期范围是件好事。此外,如果它们在根范围内,它们将永远不会释放。