Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac scope lifetime issue

Tags:

autofac

I have ASP.NET MVC application where I registered a component with an InstancePerHttpRequest scope.

builder.RegisterType<Adapter>().As<IAdapter>().InstancePerHttpRequest();

then I have an async piece of code where I'm resolving the Adapter component.

The following code is simplified

Task<HttpResponseMessage> t = Request.Content.ReadAsMultipartAsync(provider).ContinueWith(t =>

      // IHandleCommand<T> takes an IAdapter as contructor argument
      var h = DependencyResolver.Current.GetServices<IHandleCommand<T>>();
);

The code above is throwing an exception: The request lifetime scope cannot be created because the HttpContext is not available.

So I did some research on the subject and found this answer https://stackoverflow.com/a/8663021/1003222

Then I adjusted the resolving code to this

 using (var c= AutofacDependencyResolver.Current.ApplicationContainer.BeginLifetimeScope(x => x.RegisterType<DataAccessAdapter>().As<IDataAccessAdapter>).InstancePerLifetimeScope()))
 {
       var h = DependencyResolver.Current.GetServices<IHandleCommand<T>>();
 }

But the exception stayed the same. The request lifetime scope cannot be created because the HttpContext is not available.

Am I missing something ?

like image 249
user49126 Avatar asked Feb 24 '13 09:02

user49126


1 Answers

you can try something like this:

using (var c= AutofacDependencyResolver.Current
                                       .ApplicationContainer
                                       .BeginLifetimeScope("AutofacWebRequest"))
{
   var h = DependencyResolver.Current.GetServices<IHandleCommand<T>>();
}
like image 174
KozhevnikovDmitry Avatar answered Oct 07 '22 02:10

KozhevnikovDmitry