代理使用Ninject.Extensions.Interception.Linfu公开多个接口

时间:2012-04-24 17:15:21

标签: c# proxy ninject-interception linfu

我正在使用Ninject.Extensions.Interception(更具体地,InterceptAttribute)和Ninject.Extensions.Interception.Linfu代理在我的C#应用​​程序中实现日志记录机制,但是当代理类实现时我遇到了一些问题几个接口。

我有一个实现接口的类,它继承自抽象类。

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(){ ... }
}    

当我尝试从ServiceLocator获取MyClass实例时, Loggable 属性会导致它返回代理。

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

问题是返回的代理只识别 AbstractClass 接口,暴露 SomeMethod()。因此,当我尝试访问不存在的 SomeProperty 时,我收到ArgumentException

//ArgumentException
proxy.SomeProperty = "Hi";

在这种情况下,有没有办法使用mixin或其他技术创建一个暴露多个接口的代理?

由于

圣保罗

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,我没有找到一个只有ninject方法的优雅解决方案。所以我用OOP的一个更基本的模式解决了这个问题:组合。

应用于您的问题,这是我的建议:

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
    }
}
相关问题