Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Bjarne Fyrstenborg 1140 posts 3230 karma points MVP 3x c-trib
    Sep 19, 2018 @ 06:55
    Bjarne Fyrstenborg
    0

    Access UmbracoContext in Hangfire

    I have a Hangfire background task to export some data from Umbraco daily. It seems Hangfire needs to have a parameter constructor to execute the method/task in this class.

    It works with the following, when using ContextHelper.EnsureUmbracoContext(), but maybe there is a better way to handle this?

    public class ExportService
    {
        private readonly ApplicationContext _applicationContext;
        private readonly UmbracoContext _umbracoContext;
        private readonly ILogger _logger;
    
        //public GeckoExportService() : this(UmbracoContext.Current)
        //{
    
        //}
    
        // Hangfire needs a parameterless constructor
        public ExportService()
        {
            _umbracoContext = ContextHelper.EnsureUmbracoContext();
        }
    
        public ExportService(UmbracoContext umbracoContext)
        {
            _umbracoContext = umbracoContext ?? throw new ArgumentNullException("umbracoContext");
    
            _applicationContext = _umbracoContext.Application;
    
            _logger = _applicationContext.ProfilingLogger.Logger;
        }
    
        public void ExportData()
        {
    
        }
    }
    

    ...

    public static class ContextHelper
    {
        public static UmbracoContext EnsureUmbracoContext()
        {
            if (UmbracoContext.Current != null)
                return UmbracoContext.Current;
    
            var dummyHttpContext = new HttpContextWrapper(new HttpContext(new SimpleWorkerRequest("/", string.Empty, new StringWriter())));
    
            return UmbracoContext.EnsureContext(dummyHttpContext,
                    ApplicationContext.Current,
                    new WebSecurity(dummyHttpContext, ApplicationContext.Current),
                    UmbracoConfig.For.UmbracoSettings(),
                    UrlProviderResolver.Current.Providers,
                    false);
        }
    }
    

    and then in Umbraco then following Hangfire configuration:

    public class UmbracoStandardOwinStartup : UmbracoDefaultOwinStartup
    {
        public override void Configuration(IAppBuilder app)
        {
            // Ensure the default options are configured
            base.Configuration(app);
    
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/")
            });
    
            // Configure the database where Hangfire is going to create its tables
            var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = true };
            var connectionString = ApplicationContext.Current.DatabaseContext.ConnectionString;
            GlobalConfiguration.Configuration.UseSqlServerStorage(connectionString, options);
    
            // Configure Hangfire dashboard
            var dashboardOptions = new DashboardOptions { Authorization = new[] { new UmbracoAuthorizationFilter() } };
            app.UseHangfireDashboard("/hangfire", dashboardOptions);
    
            // Create a default Hangfire server
            app.UseHangfireServer();
    
            // Schedule jobs
            var scheduler = new ScheduleHangfireJobs();
            scheduler.ExportData();
        }
    
    }
    
    public class ScheduleHangfireJobs
    {
        RecurringJobManager manager = new RecurringJobManager();
    
        [DisableConcurrentExecution(timeoutInSeconds: 60)]
        [AutomaticRetry(Attempts = 3)]
        public void ExportData()
        {
            string timer = "00 23 * * *";
    
            var service = new ExportService(UmbracoContext.Current);
    
            manager.AddOrUpdate("Fetch Data", Job.FromExpression(() => service.ExportData()), timer);
        }
    }
    

    /Bjarne

  • John Bergman 430 posts 983 karma points
    Sep 19, 2018 @ 07:04
    John Bergman
    0

    Hey Bjarne,

    We do something similar. Instead of determining how to get the umbraco context inside of the hangfire task, I actually wrote it as a "maintenance" page in the CMS, then the background task simply calls the web page to do the work. Made implementation a breeze :-).

Please Sign in or register to post replies

Write your reply to:

Draft