Search code examples
c#dependency-injectionautofaccastle-dynamicproxy

Autofac DynamicProxy with type parameters


I want to use Autofac's type interception to cache method results.

I registered my types with code below

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

And it works fine. But this is Interface interception. When i register types with

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

I get error

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Castle.Proxies.MyServiceProxy' can be invoked with the available services and parameters: Cannot resolve parameter 'System.String ' of constructor 'Void .ctor(Castle.DynamicProxy.IInterceptor[], System.String, System.String, NLog.ILogger)'.

My params list is equal in both cases and is enough to create MyService and looks like

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

Have i forgot something?


Solution

  • The interceptors get wrapped around services (the As<T> part), not components (the concrete thing getting registered). You're registering things as interfaces but you're not enabling interface interception, you're enabling class interception. There aren't any classes to intercept.

    Either also add .AsSelf() to that registration statement or switch back to EnableInterfaceInterceptors().