我有 ASP.NET MVC 应用程序,我在其中注册了一个具有InstancePerHttpRequest作用域的组件。
builder.RegisterType<Adapter>().As<IAdapter>().InstancePerHttpRequest();
Run Code Online (Sandbox Code Playgroud)
然后我有一段异步代码,我正在解析适配器组件。
下面的代码是简化的
Task<HttpResponseMessage> t = Request.Content.ReadAsMultipartAsync(provider).ContinueWith(t =>
// IHandleCommand<T> takes an IAdapter as contructor argument
var h = DependencyResolver.Current.GetServices<IHandleCommand<T>>();
);
Run Code Online (Sandbox Code Playgroud)
上面的代码抛出异常: The request lifetime scope cannot be created because the HttpContext is not available.
所以我对这个主题做了一些研究,找到了这个答案 /sf/answers/606411501/
然后我将解析代码调整为此
using (var c= AutofacDependencyResolver.Current.ApplicationContainer.BeginLifetimeScope(x => x.RegisterType<DataAccessAdapter>().As<IDataAccessAdapter>).InstancePerLifetimeScope()))
{
var h = DependencyResolver.Current.GetServices<IHandleCommand<T>>();
}
Run Code Online (Sandbox Code Playgroud)
但例外情况保持不变。 The request lifetime scope cannot be created because the HttpContext is not available.
我错过了什么吗?
你可以尝试这样的事情:
using (var c= AutofacDependencyResolver.Current
.ApplicationContainer
.BeginLifetimeScope("AutofacWebRequest"))
{
var h = DependencyResolver.Current.GetServices<IHandleCommand<T>>();
}
Run Code Online (Sandbox Code Playgroud)