1

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()を公開していることです。その結果、存在しない SomePropertyArgumentExceptionにアクセスしようとすると、エラーが発生します。

//ArgumentException
proxy.SomeProperty = "Hi";

この場合、複数のインターフェイスを公開するプロキシを作成するために mixin またはその他の手法を使用する方法はありますか?

ありがとう

パウロ

4

1 に答える 1

0

私は同様の問題に遭遇しましたが、単純な手段だけでエレガントな解決策を見つけることができませんでした。そこで、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
    }
}
于 2013-01-10T00:02:16.423 に答える