Say I have an interface IInterface. Say I have 2 implementations of the same IInterface (foo & bar). Is it possible to invoke the same method on both targets?
A:
It depends how you approach it,
Generally its not possible (which return value should be returned?), but nothing stops you from having another target wrapped in an interceptor, and having it invoked by the interceptor.
Krzysztof Koźmic
2010-01-19 08:10:54
How can I have another target wrapped and getting it invoked in semi-automatic fashion like it happens when I call Proceed()?Typical scenario (taken from your nicely written tutorial!): IStorage with backup storage. You might want to read from one of them but you want to execute writes/updates to both. This is very close to what I am trying to accomplish without any external data propagation.
Paperino
2010-01-19 17:19:55
in case like this, I'd just have an explicit Write/Update interceptor that would wrap the other target, intercept Write/Update methods and propagate them to its target before proceeding with the actual invocation.
Krzysztof Koźmic
2010-01-20 12:28:23
A:
I came up with this, but it uses reflection so it's not as good as "native" support for Y-adapter type of proxy...
public void Intercept(IInvocation invocation)
{
invocation.Proceed();
ThreadPool.QueueUserWorkItem(new WaitCallback(
(object o) =>
{
invocation.Method.Invoke(newTarget, invocation.Arguments);
}
)
);
}
Using the QueueUserWorkItem guarantees that the thread invoking the method is not going to suffer much in terms of performance... Any better solution is more than welcome!
Paperino
2010-01-20 00:39:46