I am doing a migration and have encountered an exception. Autofac can resolve my service from an instance of a service provider, but cannot get it in my controller at the time of the request.
Exception: Castle.DynamicProxy.ProxyGe nerationException: This is a DynamicProxy2 error: Target type for the proxy implements Castle.DynamicProxy.IP roxyTargetAccessor which is a DynamicProxy infrastructure interface and you should never implement it yoursel f. Are you trying to proxy an existing proxy?
My AutoregistrableModule looks like that:
public class AutoregisterableModule : Autofac.Module
{
private readonly string _nameFilter;
/// <summary>
/// Default ctor
/// </summary>
/// <param name="nameFilter">Load will only search assemblies with names that contains filter</param>
public AutoregisterableModule(string nameFilter)
{
_nameFilter = nameFilter;
}
/// <summary>
/// Register's dependencies
/// </summary>
protected override void Load(ContainerBuilder builder)
{
var assemblies = new List<Assembly>();
var dependencies = DependencyContext.Default.RuntimeLibraries.Where(x => x.Name.Contains(_nameFilter));
foreach (var library in dependencies)
{
var assembly = Assembly.Load(new AssemblyName(library.Name));
assemblies.Add(assembly);
}
builder.Register(c => new LogInterceptor()).InstancePerLifetimeScope();
var isProd = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production";
var containerBuilder = builder.RegisterAssemblyTypes(assemblies.ToArray())
.Where(TypesToRegisterFilter)
.PreserveExistingDefaults()
.AsImplementedInterfaces();
if (!isProd)
{
containerBuilder.EnableInterfaceInterceptors();
}
base.Load(builder);
}
private static bool TypesToRegisterFilter(Type type)
{
return !type.IsSubclassOf(typeof(SwaggerConfigureOptions)) && !typeof(BackgroundService).IsAssignableFrom(type);
}
}
If I remove that row all works well(except of my LoggerInterceptor :D)
containerBuilder.EnableInterfaceInterceptors();
My service looks like
[Intercept(typeof(LogInterceptor))]
public class CategoriesService : ICategoriesService
{
// some code here
}
I tried to fix it by downgranding Autofac.Extensions.DependencyInjection package from 6.0.0 to 5.0.1 as were suggested there but it didn't help.
You can find full Stacktrace there https://pastebin.com/YCAhLQv0 .
So the question is how can I fix the exception and keep my interceptor working?
Fixed by raising Autofac.Extras.DynamicProxy package version from 4.5.0 to 5.0.0. Hope it may help someone.