Autofac 无法解析 class

Autofac cannot resolve class

我正在为后端构建一个使用 ASP.Net MVC 的应用程序。 Autofac 被用于依赖注入。几个 components/classes 注册为 InstancePerRequest。 Entity Framework 上下文和工作单元(只是一个调用 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();

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

{"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 articles. From what I've read, I guess the exception is being thrown due to the scopes that do not match (as described here)。如果有人能够解释为什么我会收到此错误,我将不胜感激。

非常感谢。

IAuthOrchestration 对注册为 InstancePerHttpRequestIFoo 具有间接依赖性。 要(直接或间接)解决 IFoo 你必须使用 request ILifetimeScope

您创建了一个 ILifetimeScope 而不是 RequestLifetimeScope。要创建这样的 ILifetimeScope,您可以使用 MatchingScopeLifetimeTags.RequestLifetimeScope` 标签。

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