Question

I inherited a large project written in WinForms where I have to carry a lot of small changes. I wanted to use AOP (Castle.DynamicProxy and Autofac), which so far has not caused me a problem. I wrote a simple Aspect:

class TestAspect : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine("Satrt method" + invocation.Method.Name);
        invocation.Proceed();
        Console.WriteLine("Stop funkcji " + invocation.Method.Name);
    }
}

Next, I register types in ContainerBuilder. For example:

builder.RegisterType<SomeClass>().As<ISome>().EnableInterfaceInterceptors().InterceptedBy(typeof(TestAspect)); 
builder.RegisterType<TestAspect>();

So far, so good. But I must add this aspect to legacy code (which is not written well). I had to add the aspect code(not only this above) explicitly to WinForms. For example I have button which starts method CalculateSomething (in current Window not in class). In ContainerBuilder I register current Form:

builder.RegisterType<Form1>().EnableClassInterceptors().InterceptedBy(typeof(TestAspect));

But EnableClassInterceptors() works only for virtual method. I know that the old code needs refactoring but the customer already uses this program. We rewrite this code, but we need to do some changes fast. I have two solutions:

  1. Make all methods as virtual (very bad solution)
  2. Add manually this Aspect code to every method (even worse solution)

Of course, as soon as we refactor lagacy code we do it right. But what do now? Maybe someone have any idea?

Was it helpful?

Solution

Castle DynamicProxy is limited by the polymorphism features of .NET. This means either an interface proxy which is effectively a decorator around your implementation class, or a class proxy which subclasses your implementation class and overrides virtual methods.

One other option, would be some kinda post-compilation IL-weaving that adds the behavior to the IL. This would ultimately look like your second suggestion, except it's being done by a program and not the programmer. Look into http://www.postsharp.net/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top