?
Solved

Instantiating class at run time

Posted on 2003-03-20
8
Medium Priority
?
361 Views
Last Modified: 2010-04-15
Is it possible to instantiate a class whose name I'll know only at run time? For example, I have a list of classes, either in a configuration file or in a database that lists classes all derived from an interface. How can I instantiate these at run time, similar to what Java does with the JDBC Class.forName method.

Thanks!
0
Comment
Question by:athomas4219
7 Comments
 
LVL 18

Expert Comment

by:testn
ID: 8178782
You can see sample code from
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemActivatorClassCreateInstanceTopic.asp

Basically, you'll need to import System.Reflection and then call Activator.CreateInstance("assembly.dll",
"namespace.namespace2.classname", true, BindingFlags.Instance|BindingFlags.Public, null, args, null, activationAttributes, null), it will return an object. Then you can cast it to the object that you want.

however, this is a bit unlike Class.forName.  Activator.CreateInstance will create an object directly which is what you want :D
0
 

Expert Comment

by:Shiva217
ID: 8181155
there is another way of doing this..

Assembly.CreateInstance();

e.g.

object myInstance = myAssembly.CreateInstance("MyNamespace.MyClass");



To get an instance of an Assembly object you can do:

Assembly myAssembly = Assembly.LoadFrom("assemblyPathname.dll");



Once you have your instance of your object you can manipulate it, ie call methods on it:


MethodInfo myMethodInfo = myInstance.GetType().GetMethod("MethodIWantToExecute");
object resultOfMethod = myMethodInfo.Invoke(myInstance, new object[] {"a string parameter", 12, true});

the object[] is the parameters passed into the method. To find these out at runtime, you can use:

myMethodInfo.GetParameters() // this returns a ParameterInfo[]

Hope this helps.
0
 

Author Comment

by:athomas4219
ID: 8567458
I tried the following code and received an error, which also follows:

Code:

                  object session = null;
                  object[] sessionArgs = { "username", "password", "repository" };

                  try
                  {
                        session = Activator.CreateInstance( @"C:\Source\Radix\Base\bin\Release\Base.dll", "Iminformation.Radix.Base.RdxSession", true, BindingFlags.Instance | BindingFlags.Public, null, sessionArgs, null, null, null );
                        Console.WriteLine( "Session has been created." );
                  }
                  catch( Exception e )
                  {
                        Console.WriteLine( "Error creating instance:\n\t{0}", e.Message );
                        return;
                  }

Error:

File or assembly name C:\Source\Radix\Base\bin\Release\Base.dll, or one of its dependencies, was not found.

Any thoughts?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Expert Comment

by:Shiva217
ID: 8583568
Yes,

the problem is, base.dll references something (ie another dll) that the program you're writing doesnt reference... hmm, let me try and explain AppDomains.

Each program is contained within its own application domain (the class representing this is AppDomain), all assemblies (ie dll's exe's) that are needed such as System.dll are loaded into your AppDomain, now, the dll Base.dll is referencing a dll that isnt in your application.

I know how to load up the assemblies required, but I only know how to do this is you were using the technique i listed above... let me know if you are,  then I'll post the method.

(also, there is one other possibility, you have the dll file path wrong.. but i assume that is not the case)
0
 

Author Comment

by:athomas4219
ID: 8592115
I wonder if maybe a little explanation is in order. What I'm trying to do is this: I am writing an application that has a navigation bar. Parts of this navigation bar (a TreeView) or rendered differently based on the functionality, or module, as I call it, in each position. For example, I have an Inbox and a Search module. My goal is to be able to write an interface, IModule, that will allow each of these to be rendered differently, depending on the reqruirements of the module. I want to allow the user/developer to write his own assembly, inherit from IModule, and put a line in a database table. I then want the rendering code to instantiate the user/developer's class and use the IModule interface to render the TreeView. As such, I need to be able to instantiate a class at run-time and call methods on it.

What's the best way to do this?

Thanks!
0
 

Author Comment

by:athomas4219
ID: 8600925
Here's what I ended up doing:

Assembly moduleAssembly = Assembly.LoadFrom( "AssemblyName.dll" );
Type moduleType     = moduleAssembly.GetType( "My.Namespace.Class.Name" );

myInterfaceObject = (IMyInterface)Activator.CreateInstance( moduleType, null );

// Call a method on my newly created object
moduleImpl.Render( "argument1", "argument2" );

This was what I'd wanted and, after research, it turned out to be as easy as I'd hoped and expected.

Thanks!
0
 

Accepted Solution

by:
modulo earned 0 total points
ID: 11805723
PAQed, with points refunded (35)

modulo
Community Support Moderator
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
The Relationships Diagram is a good way to get an overall view of what a database is keeping track of. It is also where relationships are defined. A relationship specifies how two tables connect to each other. As you build tables in Microsoft Ac…
Suggested Courses
Course of the Month12 days, 17 hours left to enroll

578 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question