Proxy exposing multiple interfaces with Ninject.Extensions.Interception.Linfu

377 views Asked by At

I'm using Ninject.Extensions.Interception (more specifically, InterceptAttribute) and Ninject.Extensions.Interception.Linfu proxying to implement a logging mechanism in my C# app, but I am facing some problems when a proxied class implements several interfaces.

I've a class which implements an interface and inherits from an abstract class.

public class MyClass : AbstractClass, IMyClass {
  public string SomeProperty { get; set; }
}


public class LoggableAttribute : InterceptAttribute { ... }

public interface IMyClass {
  public string SomeProperty { get; set; }
}

public abstract class AbstractClass {

  [Loggable]
  public virtual void SomeMethod(){ ... }
}    

When I try to get an instance of MyClass from ServiceLocator, the Loggable attribute causes it to return a proxy.

var proxy = _serviceLocator.GetInstance<IMyClass>();

The problem is the proxy returned only recognizes the AbstractClass interface, exposing SomeMethod(). Consequentially, I receive an ArgumentException when I try to access the inexistent SomeProperty.

//ArgumentException
proxy.SomeProperty = "Hi";

In this case, is there a way of using mixin or some other technique to create a proxy exposing multiple interfaces?

Thanks

Paulo

1

There are 1 answers

0
Firzen On

I ran in a similar problem and i did not found a elegant solution with only ninject means. So i tackled the problem with a more basic pattern from OOP: composition.

Applied to your problem something like this would be my suggestion:

public interface IInterceptedMethods
{
    void MethodA();
}

public interface IMyClass
{
    void MethodA();
    void MethodB();
}

public class MyInterceptedMethods : IInterceptedMethods
{
    [Loggable]
    public virtual void MethodA()
    {
        //Do stuff
    }
}

public class MyClass : IMyClass
{
    private IInterceptedMethods _IInterceptedMethods;
    public MyClass(IInterceptedMethods InterceptedMethods)
    {
        this._IInterceptedMethods = InterceptedMethods;
    }
    public MethodA()
    {
        this._IInterceptedMethods.MethodA();
    }
    public Method()
    {
        //Do stuff, but don't get intercepted
    }
}