具有类型参数的Autofac DynamicProxy

问题描述 投票:1回答:1

我想使用Autofac的类型拦截来缓存方法结果。

我用下面的代码注册了我的类型

builder.RegisterAssemblyTypes(dependentAssemblies)
            .Where(x => x.GetCustomAttributes(typeof(InterceptAttribute), true).Any())
            .WithParameters(parameters)
            .AsImplementedInterfaces()
            .EnableInterfaceInterceptors()
            .InstancePerRequest();

它工作正常。但这是Interface拦截。当我注册类型时

builder.RegisterAssemblyTypes(dependentAssemblies)
            .Where(x => x.GetCustomAttributes(typeof(InterceptAttribute), true).Any())
            .WithParameters(parameters)
            .AsImplementedInterfaces()
            .EnableClassInterceptors()
            .InstancePerRequest();

我收到错误

使用可用的服务和参数可以调用在'Castle.Proxies.MyServiceProxy'类型上找到'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'的构造函数:无法解析构造函数'Void .ctor'的参数'System.String' (Castle.DynamicProxy.IInterceptor [],System.String,System.String,NLog.ILogger)'。

我的参数列表在两种情况下都相同,并且足以创建MyService并且看起来像

var parameters = new[]
        {
            new NamedParameter("name1", "value1"),
            new NamedParameter("name2", "value2")
        };

我忘记了什么吗?

c# dependency-injection autofac castle-dynamicproxy
1个回答
2
投票

拦截器围绕着服务(As<T>部分),而不是组件(具体的东西被注册)。您将事物注册为接口,但是您没有启用接口拦截,您正在启用类拦截。没有任何课程可以拦截。

也可以将.AsSelf()添加到该注册声明或切换回EnableInterfaceInterceptors()

© www.soinside.com 2019 - 2024. All rights reserved.