Service without service for asp.net application

    Sometimes it may be necessary to have a service next to an asp.net application that sends out mail or just does some operations at regular intervals. This can be done using the windows service, but not all hosting providers allow them to be installed and they are not very convenient to debug (for my taste). I found on the net an interesting way to do without a service and I want to share it. Perhaps this is a well-known thing, but in the search I did not find anything about it.



    The idea is to put an object in the cache when the application starts, and repeat the procedure again when it’s “dead”. Doing it in global.asax Simplified, the code will look like this:
    protected void Application_Start(object sender, EventArgs e)
    {

    HttpContext.Current.Cache.Add("ServiceCacheKey", "Dummy", null, DateTime.MaxValue, TimeSpan.FromMinutes(1), CacheItemPriority.Normal, new CacheItemRemovedCallback(CacheItemRemovedCallback));

    }


    Now, in the CacheItemRemovedCallbak itself, you can make the necessary "service" actions and start the process of placing the object in the cache. Since HttpContext is not available at this moment, we will call some page, and at the time of calling this page put the object in the cache. That's all. The only thing that bothers me is that now every request will be checked to see if the right page has been called up and whether it is necessary to put a “service” object in the cache - I don’t know how this will affect performance.

    public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
    {

    //do service work

    WebClient wc = new WebClient();
    wc.DownloadData(SecretPageURL);
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
    if ((HttpContext.Current.Request.Url.OriginalString == SiteSettings.ServiceCacheKeyURL) && (HttpContext.Current.Request.IsLocal == true))
    {
    HttpContext.Current.Cache.Add("ServiceCacheKey", "Dummy", null, DateTime.MaxValue, TimeSpan.FromMinutes(1), CacheItemPriority.Normal, new CacheItemRemovedCallback(CacheItemRemovedCallback));
    }
    }



    Also popular now: