Loading a class at runtime from an assembly
-
Hi, Just wondering if someone could point me in the right direciton. What I am looking to achieve is to be able to dynamically load a class from an assembly at runtime, to achieve what use to be done using a ProgID/GUID to access a COM object. If someonce could give me a quick overview of the techniques that I should be looking at, that would be great. Cheers AJ
-
Hi, Just wondering if someone could point me in the right direciton. What I am looking to achieve is to be able to dynamically load a class from an assembly at runtime, to achieve what use to be done using a ProgID/GUID to access a COM object. If someonce could give me a quick overview of the techniques that I should be looking at, that would be great. Cheers AJ
Check out the Activator class. I use Activator.CreateInstanceFrom in some of my code. It seems to work really well. TF Tim Friesen tntfriesen1@hotmail.com
-
Hi, Just wondering if someone could point me in the right direciton. What I am looking to achieve is to be able to dynamically load a class from an assembly at runtime, to achieve what use to be done using a ProgID/GUID to access a COM object. If someonce could give me a quick overview of the techniques that I should be looking at, that would be great. Cheers AJ
Extending on what Tim said, the
Type
is unique to each class, enum, delegate, or struct in an assembly. It contains the namespace and class name, the assembly which contains the type, and a few other pieces of information (including version, culture, and public key token (if signed - which it should be for better applications and versioning control)). This takes the place of GUIDs and ProgIDs. BesidesActivator.CreateInstance
, you can have more control over type loading by using the static methodType.GetType
. For instance, say in your application's .config file (yourapp.exe.config, which takes the place of the registry which you're not supposed to use in .NET unless necessary) you have a partial type string like "MyNamespace.MyType, MyFirstAssembly" (version information and other stuff can be left out as long as the CLR can resolve "MyFirstAssembly"). If you want to get the type before instantiating it, you can read the value out of the configuration file and callType.GetType("MyNamespace.MyType, MyFirstAssembly")
. That returns aType
which you can use to create an instance of use Reflection to get other information (such as whether or not it implements a particular plug-in interface you require before instantiating, although you could get this by using theis
keyword after instantiating, but perhaps instantiating it is pointless to you if it doesn't implement a particular interface).-----BEGIN GEEK CODE BLOCK----- Version: 3.21 GCS/G/MU d- s: a- C++++ UL@ P++(+++) L+(--) E--- W+++ N++ o+ K? w++++ O- M(+) V? PS-- PE Y++ PGP++ t++@ 5 X+++ R+@ tv+ b(-)>b++ DI++++ D+ G e++>+++ h---* r+++ y+++ -----END GEEK CODE BLOCK-----