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

本文关键字:接口 代理 Ninject Extensions Interception Linfu 使用 | 更新日期: 2023-09-27 18:32:10

我正在使用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 或其他技术来创建公开多个接口的代理?

谢谢

保罗

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

我遇到了类似的问题,但我没有找到一个只有 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
    }
}
相关文章: