Autofac作用域生存期问题 [英] Autofac scope lifetime issue

查看:288
本文介绍了Autofac作用域生存期问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有ASP.NET MVC应用程序,在其中注册了InstancePerHttpRequest范围的组件.

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.

以下代码已简化

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.

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

因此,我对该主题进行了一些研究,并找到了答案 https://stackoverflow.com/a/8663021/1003222

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>>();
 }

但是例外保持不变. The request lifetime scope cannot be created because the HttpContext is not available.

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

我想念什么吗?

推荐答案

Autofac尝试从MVC依赖关系解析器解析容器, 如果您有异步操作,则httpContext将不可用,因此DependencyResolver也将不可用.

Autofac tries to resolve the container from the MVC Dependency Resolver, If you have a async operation the httpContext won't be available so DependencyResolver won't be available either.

其中一个选项可使容器在静态变量或适当的实例中可用,并为此操作创建上下文范围.

One option in to make the container available in a static variable or a proper instance, and create a context scope for this operation.

public static IContainer Container

一旦您建立了构建器,请复制容器

once you have the builder setup, copy the container

public class ContainerConfig
{
    public static IContainer Container;
    public static void RegisterComponents()
    {
        var builder = new ContainerBuilder();
        builder.RegisterInstance(new Svc()).As<ISvc>();
        Container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(Container ));
    }
}    

然后在解析时使用静态容器配置创建所需的实例.

then when resolving use the static container config to create the instance you need.

using (var scope = ContainerConfig.Container.BeginLifetimeScope())
{
       result = ContainerConfig.Container.Resolve<T>();
}

希望有帮助

这篇关于Autofac作用域生存期问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆