I am trying to intercept calls to a class, and virtual
methods are working correctly. However, I would also like to intercept calls to the constructor
, but I think this is not possible at least in a straight-forward way, because as stipulated on the Autofac manual:
Use Virtual Methods
Class interception requires the methods being intercepted to be virtual since it uses subclassing as the proxy technique.
Quick example:
Interceptor:
public class TestInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (invocation.Method.Name == ".ctor")
Console.WriteLine("Intercepted ctor");
invocation.Proceed();
}
}
Intercepted class:
public class ClassToBeIntercepted
{
public ClassToBeIntercepted()
{
Console.WriteLine("ClassToBeIntercepted ctor");
}
public virtual void DoSomething()
{
Console.WriteLine("Doing something");
}
}
Example test:
[TestClass]
public class TestInterception
{
public TestContext TestContext { get; set; }
// Create your builder.
private static readonly ContainerBuilder builder = new();
static Hierarchy _hierarchy = (Hierarchy)LogManager.GetRepository();
private static IContainer container;
protected static ILifetimeScope scope;
[TestMethod]
public void TestConstructorInterception()
{
builder.RegisterType<TestInterceptor>();
builder.RegisterType<ClassToBeIntercepted>()
.AsSelf()
.EnableClassInterceptors()
.InterceptedBy(typeof(TestInterceptor));
using (var scope1 = builder.Build().BeginLifetimeScope())
{
scope1.Resolve<ClassToBeIntercepted>().DoSomething();
}
}
}
Is there a work around to achieving this?