解析Autofac SingleInstance仍会导致“无法创建请求生命周期范围,因为HttpContext不可用”异常

时间:2016-02-15 08:13:23

标签: c# asp.net-mvc dependency-injection asp.net-mvc-5 autofac

注意:我已经阅读了这篇文章:Autofac - The request lifetime scope cannot be created because the HttpContext is not available - due to async code?,它并不重复。

截至最近更新时,我为AutoMapper注册了一个Autofac模块:

protected override void Load(A.ContainerBuilder builder)
{
    var mapper = this.Config.CreateMapper();

    builder.RegisterInstance(this.Config).As<IConfigurationProvider>().SingleInstance();
    builder.RegisterInstance(mapper).SingleInstance();
}

编辑:根据Travis的评论,我更新了我当前的代码。所有代码都在Controller Action中。这段代码效果很好:

var config = DependencyResolver.Current.GetService<IConfigurationProvider>();

然而,这不起作用:

var mapperConfig = this.MapperConfig;

以下是定义:

public class BaseController : Controller
{
    public IConfigurationProvider MapperConfig
    {
        get
        {
            return this.Service<IConfigurationProvider>();
        }
    }
}

public static class ControllerExtension
{

    public static T Service<T>(this Controller controller) where T : class
    {
        return DependencyUtils.Resolve<T>();
    }

}

public static class DependencyUtils
{

    public static T Resolve<T>() where T : class
    {
        return DependencyResolver.Current.GetService<T>();
    }

}

旧内容:

我有以下代码(我已尝试过异步/非异步方法):

    var modelProducts = await service.GetActive()
        .ProjectTo<ProductViewModel>(this.MapperConfig)
        .ToListAsync();
    model.AppendLine("Select new products and project into ViewModel async successfully:");

MapperConfig定义:

public MapperConfiguration MapperConfig
{
    get
    {
        return this.Service<MapperConfiguration>();
    }
}

Service方法:

    public static T Service<T>(this Controller controller) where T : class
    {
        return DependencyResolver.Current.GetService<T>();
    }

抛出此异常: enter image description here

我确信DependencyResolver.Current效果很好(我也改为AutofacDependencyResolver.Current,它是同一个对象),因为在上面的行中,我成功地获得了IProductService个实例相同的解析器(我使用的是存储库模式)。我还使用了AutoMapper,Autofac,Entity Framework 6.1的最新软件包(支持SQL Server 2008)。这些代码工作正常,如果我注释掉ProjectTo行,则不会有例外:

    var model = new StringBuilder();

    var service = this.Service<IProductService>();
    model.AppendLine("Service resolved successfully");

    var products = service.Get().ToList();
    model.AppendLine("Get all products successfully");

    products = await service.Get().ToListAsync();
    model.AppendLine("Get all products async successfully");

我做错了什么?

编辑:我把电话分开了,所以可以更清楚:

    var mapperConfig = this.MapperConfig;
    var modelProducts = await service.GetActive()
        .ProjectTo<ProductViewModel>(mapperConfig)
        .ToListAsync();
    model.AppendLine("Select new products and project into ViewModel async successfully:");

异常发生在第一行var mapperConfig = this.MapperConfig;,与服务调用无关。

0 个答案:

没有答案