我有一个ASP.NET MVC应用程序,其中我使用InstancePerHttpRequest
范围注册了一个组件。
builder.RegisterType<Adapter>().As<IAdapter>().InstancePerHttpRequest();
接下来我有一个异步代码片段,我在其中解析Adapter组件。
以下代码是简化的
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 request lifetime scope cannot be created because the HttpContext is not available.
。因此,我进行了一些研究,并找到了这个答案: https://dev59.com/CV7Va4cB1Zd3GeqPMbYK#8663021。然后我将解析代码调整为以下内容。 using (var c= AutofacDependencyResolver.Current.ApplicationContainer.BeginLifetimeScope(x => x.RegisterType<DataAccessAdapter>().As<IDataAccessAdapter>).InstancePerLifetimeScope()))
{
var h = DependencyResolver.Current.GetServices<IHandleCommand<T>>();
}
但是异常仍然存在。请求生命周期范围无法创建,因为HttpContext不可用。
我是否遗漏了什么?