Tag Archives: Reflection

Proxy Objects

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.
Continue reading Proxy Objects

Flattr this!

[c#] Instantiating an object with a private constructor

Not too long ago, I needed to modify a type available in the the BCL which didn’t have a public constructor or any method for creating an instance of the object. The solution was to use reflection to invoke the type’s private constructor.

Caveat!
Most times, these types are designed with private methods for a reason. There may be internal dependencies which can cause all kinds of problems if they’re not met. Only do something like this if you’re writing tests against the constructor or exploring the capabilities of Reflection.

The ConstructorInfo Class is the one we’ll use. If your constructor is parameterless and non-public, you can instead do:

var myType = (MyType)Activator.CreateInstance(typeof(MyType), true /*nonPublic*/);

To instantiate an object from a non-public constructor with parameters, you’ll need three things:

  • the target type
  • an array of parameter types (same order as signature)
  • a reference to the constructor

Suppose your target type is defined as:

  class Example
    {
        public string Display { get; private set; }
        private Example(string msg)
        {
            Display = msg;
        }
    }

To instantiate this object, you can do the following:

      // 1. the target type
      var exampleType = typeof(Example);

      // 2. an array of parameter types (same order as signature)
      var argTypes = new Type[] { typeof(string) };

      // 3. a reference to the constructor
      // Because method signatures must be unique in parameters and return type,
      // this will return the matching constructor, or ctor will be null.
      ConstructorInfo ctor = exampleType.GetConstructor(
          BindingFlags.Instance | BindingFlags.NonPublic,
          null, argTypes, null);

      // similar to var example = new Example("You've set me privately!")
      var example = (Example)ctor.Invoke(new []{ "You've set me privately!" });

      Console.WriteLine("Example's display: {0}", example.Display);

Note:
ConstructorInfo requires FullTrust.

Flattr this!