よし、これで…
まず、次のドメイン クラス定義があるとします。
public interface IInterceptableClass
{
string FirstName { get; set; }
string LastName { get; }
string GetLastName();
}
public class InterceptableClass : IInterceptableClass
{
public string FirstName { get; set; }
public string LastName { get; private set; }
public InterceptableClass()
{
LastName = "lastname";
}
public string GetLastName()
{
return LastName;
}
}
そして、次のように定義された単純なインターセプターの動作があるとします。
internal class SampleInterceptorBehavior : IInterceptionBehavior
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
// this invokes the method at the tip of the method chain
var result = getNext()(input, getNext);
// method executed with no exceptions (yay)
if (result.Exception == null)
{
//input.Target
Console.WriteLine($"intercepting: target={input.Target.ToString()}, method={input.MethodBase.Name}");
}
else // boo..!
{
// handle exception here
Console.WriteLine($"error! message={result.Exception?.Message}");
}
return result;
}
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}
public bool WillExecute { get { return true; } }
}
Unity
次のように配線します。
static void Main(string[] args)
{
var container = new UnityContainer();
container.AddNewExtension<Interception>();
container.RegisterType<IInterceptableClass, InterceptableClass>(
new Interceptor<TransparentProxyInterceptor>(),
new InterceptionBehavior<SampleInterceptorBehavior>());
var myInstance = container.Resolve<IInterceptableClass>();
// just want to illustrate that privae sets are not supported...
myInstance.FirstName = "firstname";
var lastname = myInstance.GetLastName();
Console.ReadLine();
}
Unity を使用して傍受を接続しない場合は、これを手動で行う必要があることに注意してください。1回限りの場合、一部の開発者はその方法を好むかもしれませんが、実際には、その道は持続不可能であり、複数の傍受があり、非常に残忍であることが常にわかりました. そのため、可能であれば常に Unity を使用してください。
ただし、どうしても Unity をバイパスする必要がある場合は、次のようにします。
var manualInstance = Intercept.ThroughProxy<IInterceptableClass>(
new InterceptableClass(), // <-- this could be an already-existing instance as well...
new TransparentProxyInterceptor(),
new IInterceptionBehavior[]
{
new SampleInterceptorBehavior()
});
manualInstance.FirstName = "firstname";
var lastname = manualInstance.GetLastName();