没有匹配'AutofacWebRequest'从瞄准镜中可见

本文关键字:瞄准镜 AutofacWebRequest | 更新日期: 2023-09-27 18:17:24

新的AutoFac最近使用SimpleInjector,但因为我已经升级到vNext/。NET5, AutoFac似乎已经更新了,所以用AutoFac代替。

我想做的就是确保我的DbContext是在每个请求上创建的。我可以通过使用.InstancePerRequest()来做到这一点,但是当我这样做时(我已经添加到我所有的代码中),我似乎得到了错误信息

Autofac.Core。没有带标签的作用域匹配的'AutofacWebRequest'从作用域中可见请求实例。这通常表示一个组件按http请求注册的SingleInstance()组件(或类似的场景)。在网上集成总是从DependencyResolver。当前或ILifetimeScopeProvider。RequestLifetime,

我相信这是说有些东西没有被请求为每个http请求,所以没有什么会?对吗?如果是这样,似乎有点愚蠢。我不在乎我的服务和验证器是否只创建一次,但我需要在每个请求上创建DbContext,因为当多个请求连接到我的WebApi时,我一直得到一个错误说

在上一个上下文之前开始的第二个操作异步操作完成。

但是,如果我自己一个接一个地执行这些调用,那么它们都可以正常工作。

我使用的是EntityFramework 6.1,而不是EF7,因为EF7还远未完成。

我有AutoFac模块,像这样

public class SetupModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        // IDataContext
        builder.Register((c) =>
            {
                var appEnv = c.Resolve<IApplicationEnvironment>();
                var configBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
                    .AddJsonFile("config.json");
                var configuration = configBuilder.Build();
                return new DataContext(configuration["Data:MyConnection:ConnectionString"]);
            })
            .As<IDataContext>()
            .InstancePerRequest();
        // Validators
        builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetAssembly(typeof(IValidator)))
            .Where(t => typeof(IValidator).IsAssignableFrom(t))
            .AsImplementedInterfaces()
            .InstancePerRequest();
        // Services
        builder.RegisterType<ContentService>().As<IContentService>().InstancePerRequest();
    }
}

我的DataContext就像一个带构造函数的标准DbContext类,只是取connectionString

public DataContext : IDataContext {
    public DataContext(string connectionString)
        : base(connectionString)
        {
        }
}

在我的startup。cs文件中,我使用

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // Create the Autofac container builder.
    var builder = new ContainerBuilder();
    builder.RegisterModule(new AutoFac.SetupModule());
    builder.Populate(services);
    // Build the container.
    var container = builder.Build();
    // Resolve and return the service provider.
    return container.Resolve<IServiceProvider>();
}
谁能告诉我我到底错过了什么?是否与我如何创建我的DataContext有关,因为需要这样做才能从配置中获得connectionString。json文件。

Thanks in advance

注意:如果我改变为.InstancePerDependency()我的错误停止,但我不认为这是我想要的所有对象

更新下面是stacktrace

at Autofac.Core.Lifetime.MatchingScopeLifetime.FindScope(ISharingLifetimeScope mostNestedVisibleScope) 
at Autofac.Core.Resolving.InstanceLookup..ctor(IComponentRegistration registration, IResolveOperation context, ISharingLifetimeScope mostNestedVisibleScope, IEnumerable<Parameter> parameters)
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable<Parameter> parameters)
at Autofac.Core.Resolving.ResolveOperation.ResolveComponent(IComponentRegistration registration, IEnumerable<Parameter> parameters) 
at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable<Parameter> parameters) 
at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable<Parameter> parameters) 
at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable<Parameter> parameters, Object& instance) 
at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable<Parameter> parameters) 
at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType, IEnumerable<Parameter> parameters) 
at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType) 
at Autofac.Framework.DependencyInjection.AutofacServiceProvider.GetService(Type serviceType) 
at Microsoft.Framework.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired) 
.lambda_method(Closure , IServiceProvider , Object[] ) 
at Microsoft.AspNet.Mvc.DefaultTypeActivatorCache.CreateInstance<TInstance>(IServiceProvider serviceProvider, Type implementationType) 
at Microsoft.AspNet.Mvc.DefaultControllerActivator.Create(ActionContext actionContext, Type controllerType) 
at Microsoft.AspNet.Mvc.DefaultControllerFactory.CreateController(ActionContext actionContext) 
at Microsoft.AspNet.Mvc.Core.ControllerActionInvoker.CreateInstance() 
at Microsoft.AspNet.Mvc.Core.FilterActionInvoker.<InvokeAllActionFiltersAsync>d__49.MoveNext() 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
at Microsoft.AspNet.Mvc.Core.FilterActionInvoker.<InvokeExceptionFilterAsync>d__48.MoveNext() 
--- exception rethrown --- 
at Microsoft.AspNet.Mvc.Core.FilterActionInvoker.<InvokeAsync>d__41.MoveNext() 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
at Microsoft.AspNet.Mvc.MvcRouteHandler.<InvokeActionAsync>d__7.MoveNext() 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
at Microsoft.AspNet.Mvc.MvcRouteHandler.<RouteAsync>d__6.MoveNext() 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
at Microsoft.AspNet.Mvc.Routing.InnerAttributeRoute.<RouteAsync>d__10.MoveNext() 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
at Microsoft.AspNet.Routing.RouteCollection.<RouteAsync>d__9.MoveNext() 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
at Microsoft.AspNet.Builder.RouterMiddleware.<Invoke>d__4.MoveNext() 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
at Microsoft.AspNet.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext() 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
at Microsoft.AspNet.Hosting.Internal.HostingEngine.<>c__DisplayClass29_0.<<Start>b__0>d.MoveNext() 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
at Microsoft.AspNet.Loader.IIS.RuntimeHttpApplication.<ProcessRequestAsyncImpl>d__13.MoveNext() 
--- exception rethrown --- 
at Microsoft.AspNet.Loader.IIS.RuntimeHttpApplication.<ProcessRequestAsyncImpl>d__13.MoveNext() 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
at Microsoft.AspNet.Loader.IIS.HttpApplicationBase.<InvokeProcessRequestAsyncImpl>d__9.MoveNext()

没有匹配'AutofacWebRequest'从瞄准镜中可见

简短的回答是你不能依靠一个短命的东西来拥有一个长寿的东西

示例:单个取决于实例每个请求是坏的

所以典型的默认值是每依赖一个实例(瞬态的,所以每次你需要一个新的创建)。

,如果您有每个请求实例的AB是单例

然后A依赖于B,没问题但是如果B依赖于A,你就会遇到问题,因为B永远不会被重新创建,但依赖于每个作用域都会被重新创建的A。

其他库有时会让你犯这个错误,并自己发现它(非常痛苦)

似乎AutoFact在让你知道范围层次结构有问题方面做得更好。

似乎有两件事在发生:

  • Autofac没有正确地与ASP集成。
  • . NET尚未启动标记为AutofacWebRequest的新生存期范围。
  • 你正在解析一个在生命周期作用域中注册为InstancePerRequest()的组件,其祖先不包括标记为AutofacWebRequest的生命周期作用域。

查看堆栈跟踪,似乎第一种情况比第二种情况更可能发生,因为异常发生在控制器的构造中。