How to create an instance of a class in an ASP.NET application

How are you going to instantiate an object when specifying a class name as a string in an ASP.NET v2 application? For example, I have a class called SystemLog defined in the app_code section of the application. The class is defined in the Reports namespace. To create an instance of an object, I do something like this:

Dim MyObject As New Global.Reports.SystemLog

However, I want to create this object using a string to determine the type. The type name is stored in the SQL database as a string. I think this is probably something related to Activator.CreateInstance (AssemblyName, TypeName), but I don't know what to pass on these lines. What is the assembly name of the ASP.NET web application?

Help!

Thanks Rob.

PS. I don't want a hard-coded Select statement :-)

+5
source share
3 answers
string typeName = "Your Type Name Here";
Type t = Type.GetType(typeName);
object o = Activator.CreateInstance(t);

This will give you a specific type. If you need to direct it to the correct type and call the appropriate methods.

If you need to create a type that does not have a constructor without parameters, there is an overload on CreateInstance, which accepts object parameters to pass to the constructor. Read more about this MSDN article .

+5
source

The following method can create a type, even if it is from another assembly:

public object CreateInstance(string typeName) {
   var type = AppDomain.CurrentDomain.GetAssemblies()
              .SelectMany(a => a.GetTypes())
              .FirstOrDefault(t => t.FullName == typeName);

   return type.CreateInstance();
}
+2
source

, :

= Assembly.Load( "myAssembly" );

ObjectType = assembly.GetType( " " );

then..... object o = Activator.CreateInstance(ObjectType);

0

All Articles