How do I create a backgroung task from an MVC controller using Autofac?

Im writing a plugin for nopCommenre and facing the following problem: one of the controller action methods is to trigger a height load operation on a background thread. nopCommerce uses Autofac as its IoC container.

If I understand correctly, I need to create a new lifescope that depends on the old one to use Autofac on a background thread. I found the following solution, but it doesn't work:

    public void Run<T>(Action<T> action)
    {
        Task.Factory.StartNew(delegate
        {
            using (var container = AutofacDependencyResolver.Current.ApplicationContainer.BeginLifetimeScope("AutofacWebRequest"))
            {
                var service = container.Resolve<T>();
                action(service);
            }
        });
    }

      

I have a bug. "The request lifecycle scope could not be created because the HttpContext is not available." This answer helps me understand the reason for this behavior, but I still don't know how to resolve services using Autofac on a background thread. I cannot change the nopCommerce source code, so I cannot keep a link to the original Autofac container as mentioned above.

+3


source to share


1 answer


So you are in a background job and do not have access to the HttpContext. Hence, you cannot use EngineContext.Current.Resolve ()

In this case, if you want to get the current area, use the following code:

var scope = EngineContext.Current.ContainerManager.Scope ();

Once you use it:



EngineContext.Current.ContainerManager.Resolve ("", scope);

PS This code is executed by default for nopCommerce tasks - \ Libraries \ Nop.Services \ Tasks \ Task.cs

PPS If you didn't list your version of nopCommerce, I assume it's 3.40. This is the solution for 3.40

+3


source







All Articles