3

Im writing a plugin for nopCommenre and encountered the following problem: one of the controller's action method should run a height-load operation in background thread. nopCommerce uses Autofac as IoC container.

If I understand correctly, I need to create new lifescope dependent on old one to use Autofac in background thread. I found the following solution, but it does not 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've got an error "The request lifetime scope cannot be created because the HttpContext is not available". This answer helps me to upderstand the reason of this behaviour, but I still dont know how to resolve services using Autofac in background thread. I cant change source code of nopCommerce, so I cant save reference to the original Autofac container as adviced in answer above.

Community
  • 1
  • 1
landless
  • 133
  • 2
  • 8
  • From an Autofac perspective, there is a good article on the Autofac doc site talking about options for working with per-request scope in the background: http://autofac.readthedocs.org/en/latest/faq/per-request-scope.html – Travis Illig Aug 08 '14 at 13:38

1 Answers1

3

So you're in background task and don't have HttpContext available. Hence you cannot use EngineContext.Current.Resolve()

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

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

Once you have it use:

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

P.S. This code is from default nopCommerce tasks implementation - \Libraries\Nop.Services\Tasks\Task.cs

P.P.S. If you haven't specified your nopCommerce version, so I presume it's 3.40. This solution is for 3.40

Andrei M
  • 3,429
  • 4
  • 28
  • 35