Creating objects with out defining them — WHAT?

Lately my time has been devoted to one project, a very very cool project. That is about the depths I can go on in my blog but I can say that it involve a windows service that is basically the host for many assemblies and are accessed by webservices via .NET Remoting.

I wanted this service to be able to do 2 things. Since more and more assemblies were being added and certain customers purchased some features and other did not, I wanted it to be able to dynamically load them, getting the information from a config file and if the assembly failed during initialization, not continue the load.

My first approach:

At first I just added the singleton object in my service code, initialized and wham, all is good but this proved to be non-scalable. If I didn’t want the assembly to load (perhaps I was debugging, there was a know bug, customer didn’t purchase module, etc), it would still load and took up memory. Also when I coded newer assemblies, I would have to manually add an object reference and initialize them, maintenance nightmare.

I wanted each assembly to be autonomous, as well as the service. Neither should know ‘too much’ about each other. This way I could develop new assemblies, add them to the config file and it would load it when the service ran. Also, if I wanted to remove it, I just removed it from the config file.

My second approach:

So how did I accomplish this? With .NET Activator class and by calling its CreateInstance method, I can dynamically create an object base on a type with out defining it in the code. For example:

Class1.CClass1 objClass = new Class1.CClass1();

Is the same as

object objClass = Activator.CreateInstance(Type.GetType(“Class1.CClass1,Class1”));

These do the SAME thing yet one you have to define Class1, in the other piece of code, a string defines it. Magic I say.

Download here

~ by gordingin on September 20, 2008.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.