autofac 作用域,Autofac作用域生存期问题

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

builder.RegisterType().As().InstancePerHttpRequest();

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

The following code is simplified

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

// IHandleCommand takes an IAdapter as contructor argument

var h = DependencyResolver.Current.GetServices>();

);

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().As).InstancePerLifetimeScope()))

{

var h = DependencyResolver.Current.GetServices>();

}

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

Am I missing something ?

解决方案

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

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

}

hope it helps

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值