I've got a need to create a dynamic proxy in C#. I want this class to wrap another class, and take on it's public interface, forwarding calls for those functions:
class MyRootClass
{
public virtual void Foo()
{
Console.Out.WriteLine("Foo!");
}
}
interface ISecondaryInterface
{
void Bar();
}
class Wrapper<T> : ISecondaryInterface where T: MyRootClass
{
public Wrapper(T otherObj)
{
}
public void Bar()
{
Console.Out.WriteLine("Bar!");
}
}
Here's how I want to use it:
Wrapper<MyRootClass> wrappedObj = new Wrapper<MyRootClass>(new MyRootClass());
wrappedObj.Bar();
wrappedObj.Foo();
to produce:
Bar!
Foo!
Any ideas?
What's the easiest way to do this?
What's the best way to do this?
Thanks so much.
UPDATE
I tried following Wernight's recommendation and implement this using C# 4.0 dynamic proxies. Unfortunately, I'm still stuck. The point of the proxy is to mimick the other interface which is (normally, usually) expected. Using DynamicObject requires me to change all the clients of this to use 'dynamic' instead of 'ISecondaryInterface'.
Is there a way to get a proxy object, such that when it wraps an A, it advertises (statically?) that it supports A's interface; and when it wraps a B, it advertises that is supports B's interface?
UPDATE 2
For example:
class MySecretProxy : DynamicObject, ISecondaryInterface
{
public override void TryInvokeMember(...) { .. }
// no declaration of Bar -- let it be handled by TryInvokeMember
}
You can do this with RealProxy if the target Type is an interface or derives from MarshalByRefObject.
Have you looked at the Castle project's DynamicProxy? It may provide what you're ultimately trying to achieve. See http://www.castleproject.org/dynamicproxy/index.html
It's also open source so you could even fork it if required.
I know the proxies that used by nhibernate for lazy loading
Castle
Linfu
Spring ByteCode
.NET 4
DynamicObject
can help you achieving that.Earlier .NET framework can use:
See the full article.
I know that Castle Project's Dynamic Proxy is often used (like in Moq just to name one large project).
REPLY TO UPDATED TOPIC
What you wrote will not compile. Dynamic proxies are runtime generated code, so you'll have to create a concrete instance of the class you're proxying some way or another. May be you're looking to do AOP (aspect-oriented programming).
You may want to look at linfu which contains a dynamic proxy mechanism.