1

I want to instantiate an object of a class using Activator.CreateInstance. So, I have an ASP.Net MVC project under which i have a folder called Modal and under that i have one class TestClass.cs.

Now i have another Class Library project. So have i written the instantiation login inside one of the class of my Class Library project and copy the .dll file inside my main ASP.Net MVC project.

Now from my main project i requested to my recently add Class Library project to create an Object of the class by passing FullyQualified name of my class.

EX:

ASP.Net MVC Project

------------------------------
`
namespace MyProject.Modal
{
    public class TestClass
    {
        public TestClass()
        {
        }
    }
}
`

Class Library Project Code

`

namespace SpringNet.FactoryContext
{
   public class CreateInstance
   {        
     public Object GetClass(string FullyQualifiedName)
     {
        Object NewClassType = null;
        Type ClassName = Type.GetType(FullyQualifiedName);
        NewClassType = Activator.CreateInstance(ClassName);
        return NewClassType;
     }
   }
}

`

Now i build my Class library project and added reference to my ASP.Net MVC Project and tries to create the object.

CreateInstance instance = new CreateInstance();
var NewObject = instance.GetClass("MyProject.Modal.TestClass");

After calling this i am getting exception

  • Type ClassName = Type.GetType(FullyQualifiedName);

at this line only i am not able to get the type of class what i am requesting for.

Please help. Thanks in advance.

Dávid Molnár
  • 10,673
  • 7
  • 30
  • 55
Md IstiyaQ
  • 21
  • 3
  • You have to add reference to your class library project. – FCin Oct 30 '17 at 07:40
  • You can also load the assembly at runtime, then try to instantiate the type using `Activator.CreateInstance(ClassName)` – Sirwan Afifi Oct 30 '17 at 07:56
  • My class library is a stand alone dll file. As i am already using dll in my main project and if i will tries to add the main project reference in my Class library then it will become circular refence. – Md IstiyaQ Oct 30 '17 at 08:51
  • You cannot or at least shouldn't make them both aware of each other. You should introduce third project that they both can can reference and communicate with each other through. – FCin Oct 30 '17 at 09:00

1 Answers1

0

You can try this one:

namespace SpringNet.FactoryContext
{
   public class CreateInstance
   {        
     public Object GetClass(string assemblyName,string className)
     {
        return Activator.CreateInstance(assemblyName, className);
     }
   }
}

And then

 CreateInstance instance = new CreateInstance();
    var NewObject = instance.GetClass("MyProject", "MyProject.Modal.TestClass");

Updated: Why Type.GetType return null

Type.GetType("namespace.a.b.ClassName") returns null

Edward N
  • 997
  • 6
  • 11