Autofac无法解析课程

时间:2015-06-10 12:02:55

标签: c# asp.net-mvc entity-framework autofac

我正在使用ASP.Net MVC为后端构建应用程序。 Autofac用于依赖注入。几个组件/类注册为InstancePerRequest。实体框架上下文和工作单元(只是一个调用context.SaveChanges()的包装器)注册为InstancePerLifetimeScope。示例代码:

builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(DomainModule)))
    .Where(t => t.IsClosedTypeOf(typeof(IFooService<>)))
    .AsImplementedInterfaces()
    .AsClosedTypesOf(typeof(IFoo<>))
    .InstancePerRequest();

builder.RegisterType<FooContext>()
    .AsSelf()
    .As<IObjectContextAdapter>()
    .InstancePerLifetimeScope();

builder.RegisterType<UnitOfWork>()
    .AsImplementedInterfaces()
    .AsSelf()
    .InstancePerLifetimeScope();

使用显式范围从容器中解析类会引发以下异常:

{"No scope with a Tag matching 'AutofacWebRequest' is visible from the scopein which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself."}

触发上述异常的代码:

using (var scope = _lifetimeScope.BeginLifetimeScope())
{
    var authOrchestration = scope.Resolve<IAuthOrchestration>();
    apiClient = authOrchestration.GetApiClient(context.ClientId);
}

请注意,IAuthOrchestration未注册InstancePerRequest之类的内容,因此应默认为InstancePerDependency

我现在一直试图绕过这个问题几个小时。我已阅读these two篇文章。从我读过的内容来看,我认为由于范围不匹配而抛出异常(如here所述)。如果有人能够解释我为什么会收到这个错误,我会非常感激。

非常感谢提前。

1 个答案:

答案 0 :(得分:0)

IAuthOrchestrationIFoo有间接依赖关系,注册为InstancePerHttpRequest。 要(直接或间接)解决IFoo您必须使用请求 ILifetimeScope

您创建的ILifetimeScope不是RequestLifetimeScope。要创建此类ILifetimeScope,您可以使用MatchingScopeLifetimeTags。RequestLifetimeScope`标记。

using (var scope = _lifetimeScope
                    .BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
    var authOrchestration = scope.Resolve<IAuthOrchestration>();
    apiClient = authOrchestration.GetApiClient(context.ClientId);                
}
相关问题