I started to familiarize myself with proxy objects a couple of years ago when I started used Fluent NHibernate on a pretty large project. NHibernate itself proxies objects to allow the framework to do its magic. Proxies are a fantastic thing. I spoke with a friend of mine today about some advanced coding techniques including proxy objects and IoC, which made me want to write a little about some of those topics.
From Wikipedia:
A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
Charles Bretana gave an excellent and succinct definition of proxy objects on Stack Overflow back in 2008:
One purpose is to “pretend” to be the real class so a client component (or object) can “believe” it’s talking to the “real” object, but inside the proxy, other stuff, (like logging, transactional support, etc.) is being done at the same time… Secondly, a proxy can be very cheap in comparson to the real object,. and often is used so that the real objects can be conserved (turned off or released to a pool to be used by other clients) when the client is not using them… The proxy stays “alive” and the client thinks it still has a connection to the real object, but whenever it “calls” the object, it is actually calling the proxy, which goes and gets another real object just to handle the call, and then releases the real object when the call is done.
I’ve created an example (available on github) which demonstrates how to proxy method calls in a few different ways, ranging from very simple to using Castle.DynamicProxy and interceptors. The code is written in C# and although the code doesn’t handle some of the more advanced topics of proxy objects, such as resource pooling as Charles described, it will (I hope) introduce proxy objects in a comprehensible way.
Read on for killer examples.
... ➦I answered a question on StackOverflow nearly two years ago, and I’m surprised at how few votes it has received, despite comments such as:
+1 for teaching me something new today thanks. -kobe
Being one of my favorite answers, I thought I should discuss it on my blog a little more in-depth than just posting the SO answer. I’d like to briefly discuss what ASP.NET really is (in the context of IIS), why AppDomains are needed, and lastly what shadow-copying does for an application. There is no code associated with this post, and it is driven more by contemplation than by a specific resolution to a problem. So, I apologize in advance if it seems disjointed at times.
... ➦