【问题标题】:Autofac DynamicProxy with type parameters带有类型参数的 Autofac DynamicProxy
【发布时间】:2018-08-07 04:10:51
【问题描述】:

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

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

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

而且效果很好。 但这是接口拦截。 当我注册类型时

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(Castle.DynamicProxy.IInterceptor[], System.String, System.String, NLog.ILogger)”的参数“System.String”。

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

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

我忘记了什么吗?

【问题讨论】:

    标签: c# dependency-injection autofac castle-dynamicproxy


    【解决方案1】:

    拦截器被包裹在 servicesAs<T> 部分),而不是 components(被注册的具体事物)。您将事物注册为接口,但您没有启用接口拦截,而是启用了类拦截。没有要拦截的类。

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

    【讨论】:

    • 我可以拦截组件吗?
    • 我通过接口注入依赖项,但我需要 autofac 为组件创建代理,以处理缓存或 smth。有可能吗?
    • 你应该添加链接到你的答案,这非常有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 2011-08-10
    相关资源
    最近更新 更多