本文介绍了无法在ASP.NET Core 3.1应用程序的类/接口上连接拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

软件包:Autofac.Extensions.DependencyInjection(6.0.0),Autofac.extras.DynamicProxy(4.5.0)

Packages: Autofac.Extensions.DependencyInjection (6.0.0), Autofac.extras.DynamicProxy(4.5.0)

我正在尝试通过遵循ASP.NET Core 4.0和Interceptor文档为我们的应用程序中服务Web API控制器的所有服务类/接口设计拦截器的原型.拦截器只是使用Serlog的简单Log操作:

I am trying to prototype an interceptor for all of our service classes/interface serving the Web API controllers in our application, by following the ASP.NET Core 4.0 and the Interceptor documentation. The Interceptor is just a simple Log action using Serlog:

    public MethodCallInterceptor()
    {
    }

    public void Intercept(IInvocation invocation)
    {
        var text = invocation.Method.Name;
        Log.Logger.Debug($"Interceptor (Method): {text}");

        invocation.Proceed();
    }

我们的主应用程序将带有ComApiApplication的Autofac设置为启动"类:

Our main application sets up Autofac with ComApiApplication as the "Startup" class:

    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<ComsApiApplication>());
    }

在ComsApiApplication中,我在ConfigureServices中注册了大多数ASP.NET MVC服务(例如,身份验证,授权等).然后,我在其ConfigureContainer函数中的几个服务组合中连接了类的Interceptor:

In ComsApiApplication, I register most of ASP.NET MVC services in ConfigureServices (e.g. Authentication, Authorization etc). Then, I hook up the Interceptor for classes in a couple of our service assembles in its ConfigureContainer function:

    public void ConfigureContainer(ContainerBuilder builder)
    {
        foreach (var assembly in Options.Assemblies)
        {
            // Add application services: IService => Service.
            var registrations = assembly.GetExportedTypes()
                .Where(type => type.Namespace != null && type.Namespace.Contains(".Services") && type.GetInterfaces().Any() && !type.IsAbstract)
                .Select(type => new
                {
                    Service = type.GetInterfaces().Single(inf => inf.Name.Contains(type.Name)),
                    Implementation = type
                });

            foreach (var registration in registrations)
            {
               //builder.RegisterType(registration.Implementation).As(registration.Service).InstancePerDependency().EnableInterfaceInterceptors().InterceptedBy(typeof(MethodCallInterceptor));
                    builder.RegisterType(registration.Implementation).As(registration.Service).EnableInterfaceInterceptors().InstancePerDependency().InterceptedBy(typeof(MethodCallInterceptor));
            }
            builder.Register(c => new MethodCallInterceptor());
        }
    }

但是,当我运行带有导致调用那些服务中的接口函数的请求的应用程序时(我们的接口和服务类中存在继承关系),我得到以下异常,并且感谢您对确定问题的任何帮助:

However, when I run the application with requests leading to call the interface functions in those services (inheritance exists in our interfaces and service classes), I get the following exception and would be grateful for any help in identifying my issue:

Autofac.Core.DependencyResolutionException:执行解析操作时引发了异常.有关详细信息,请参见InnerException. ---> Castle.DynamicProxy.ProxyGenerationException:这是DynamicProxy2错误:代理的目标类型实现Castle.DynamicProxy.IProxyTargetAccessor,它是DynamicProxy基础结构接口,您永远不要自己实现它.您是否要代理现有的代理? 在Castle.DynamicProxy.Generators.BaseProxyGenerator.HandleExplicitlyPassedProxyTargetAccessor(ICollection 1 targetInterfaces, ICollection 1个额外接口)上 在Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.GetTypeImplementerMapping(Type []接口,类型proxyTargetType,IEnumerable 1& contributors, INamingScope namingScope) at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.GenerateType(String typeName, Type proxyTargetType, Type[] interfaces, INamingScope namingScope) at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.<>c__DisplayClass6_0.<GenerateCode>b__0(String n, INamingScope s) at Castle.DynamicProxy.Generators.BaseProxyGenerator.ObtainProxyType(CacheKey cacheKey, Func 3工厂) 在Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.GenerateCode(类型proxyTargetType,类型[]接口,ProxyGenerationOptions选项)处 在Castle.DynamicProxy.DefaultProxyBuilder.CreateInterfaceProxyTypeWithTarget(Type interfaceToProxy,Type [] AdditionalInterfacesToProxy,typetargetType,ProxyGenerationOptions选项) 在Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyTypeWithTarget(Type interfaceToProxy,Type [] AdditionalInterfacesToProxy,type targetType,ProxyGenerationOptions选项) at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithTarget(Type interfaceToProxy,Type [] AdditionalInterfacesToProxy,对象目标,ProxyGenerationOptions选项,IInterceptor []拦截器) 在Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithTarget(Type interfaceToProxy,Type [] AdditionalInterfacesToProxy,Object target,IInterceptor []拦截器) 在Autofac.Extras.DynamicProxy.RegistrationExtensions中.<> c__DisplayClass9_0 3.<EnableInterfaceInterceptors>b__0(Object sender, ActivatingEventArgs 1 e) 在Autofac.Core.Registration.ComponentRegistration.RaiseActivating(IComponentContext上下文,IEnumerable 1 parameters, Object& instance) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable 1参数,Object& decoratorTarget)中 在Autofac.Core.Resolving.InstanceLookup.Execute() 在Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope,ResolveRequest请求) 在Autofac.Core.Resolving.ResolveOperation.ResolveComponent(ResolveRequest请求) 在Autofac.Core.Resolving.ResolveOperation.Execute(ResolveRequest请求) ---内部异常堆栈跟踪的结尾--- 在Autofac.Core.Resolving.ResolveOperation.Execute(ResolveRequest请求) 在Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(ResolveRequest请求) 在Autofac.ResolutionExtensions.TryResolveService(IComponentContext上下文,服务服务,IEnumerable 1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable 1参数) 在Autofac.ResolutionExtensions.ResolveOptional(IComponentContext上下文,类型serviceType,IEnumerable`1参数) 在Autofac.ResolutionExtensions.ResolveOptional(IComponentContext上下文,类型serviceType) 在Autofac.Extensions.DependencyInjection.AutofacServiceProvider.GetService(类型serviceType) 在Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,Boolean isDefaultParameterRequired) 在lambda_method(Closure,IServiceProvider,Object []) 在Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider处.<> c__DisplayClass4_0.b__0(ControllerContext controllerContext) 在Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider处.<> c__DisplayClass5_0.g__CreateController | 0(ControllerContext controllerContext) 在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next,Scope&范围,Object&状态,Boolean& isCompleted) 在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()---从上一个引发异常的位置开始的堆栈结束跟踪--- 在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited | 25_0(ResourceInvoker调用程序,Task lastTask,Next状态,Scope作用域,对象状态,布尔值isCompleted)Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor:信息:正在执行JsonResult,写入类型为'System.String'的值.

Autofac.Core.DependencyResolutionException: An exception was thrown while executing a resolve operation. See the InnerException for details. ---> Castle.DynamicProxy.ProxyGenerationException: This is a DynamicProxy2 error: Target type for the proxy implements Castle.DynamicProxy.IProxyTargetAccessor which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to proxy an existing proxy? at Castle.DynamicProxy.Generators.BaseProxyGenerator.HandleExplicitlyPassedProxyTargetAccessor(ICollection1 targetInterfaces, ICollection1 additionalInterfaces) at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.GetTypeImplementerMapping(Type[] interfaces, Type proxyTargetType, IEnumerable1& contributors, INamingScope namingScope) at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.GenerateType(String typeName, Type proxyTargetType, Type[] interfaces, INamingScope namingScope) at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.<>c__DisplayClass6_0.<GenerateCode>b__0(String n, INamingScope s) at Castle.DynamicProxy.Generators.BaseProxyGenerator.ObtainProxyType(CacheKey cacheKey, Func3 factory) at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.GenerateCode(Type proxyTargetType, Type[] interfaces, ProxyGenerationOptions options) at Castle.DynamicProxy.DefaultProxyBuilder.CreateInterfaceProxyTypeWithTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, Type targetType, ProxyGenerationOptions options) at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyTypeWithTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, Type targetType, ProxyGenerationOptions options) at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, Object target, ProxyGenerationOptions options, IInterceptor[] interceptors) at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, Object target, IInterceptor[] interceptors) at Autofac.Extras.DynamicProxy.RegistrationExtensions.<>c__DisplayClass9_03.<EnableInterfaceInterceptors>b__0(Object sender, ActivatingEventArgs1 e) at Autofac.Core.Registration.ComponentRegistration.RaiseActivating(IComponentContext context, IEnumerable1 parameters, Object& instance) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request) at Autofac.Core.Resolving.ResolveOperation.ResolveComponent(ResolveRequest request) at Autofac.Core.Resolving.ResolveOperation.Execute(ResolveRequest request) --- End of inner exception stack trace --- at Autofac.Core.Resolving.ResolveOperation.Execute(ResolveRequest request) at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(ResolveRequest request) at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable1 parameters) at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType, IEnumerable`1 parameters) at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType) at Autofac.Extensions.DependencyInjection.AutofacServiceProvider.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired) at lambda_method(Closure , IServiceProvider , Object[] ) at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.b__0(ControllerContext controllerContext) at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.g__CreateController|0(ControllerContext controllerContext) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()--- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor: Information: Executing JsonResult, writing value of type 'System.String'.

推荐答案

以下内容来自Google翻译:碰巧的是,我只是解决了这个问题,但这不是正确的解决方案.只需将Autofac.Extensions.DependencyInjection包降级为 5.0.1 即可解决问题.

The following is from Google Translate:Coincidentally, I just solved this problem, but this is not the correct solution.Just need to downgrade the Autofac.Extensions.DependencyInjection package to 5.0.1 to solve the problem.

这篇关于无法在ASP.NET Core 3.1应用程序的类/接口上连接拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 17:28