citronas
citronas

Reputation: 19365

Create an object via reflection from a satellite assembly

I have two assemblies / projects with DLL as output: Models and Logic

Inside the Logic DLL I want to create an object of a specific model via reflection (The project is referenced and I am able to manually create an instance)

MyNameSpace.Models.Foo foo = new MyNameSpace.Models.Foo(); // works
Type type = Type.GetType("MyNameSpace.Models.Foo"); // returns null

How can I create an object of MyNameSpace.Models.Foo? Apparently the type does not resolve. How can I fix this?

Upvotes: 1

Views: 954

Answers (3)

Jason Evans
Jason Evans

Reputation: 29186

You could look at using Activator.CreateInstance. For example:

Assembly assembly = Assembly.LoadFrom("Foo.dll");

Type type = assembly.GetType("TheNamspace.TheType");

object instanceOfMyType = Activator.CreateInstance(type);

Upvotes: 1

VikciaR
VikciaR

Reputation: 3412

Type.GetType argument is AssemblyQualifiedName: from MSDN

Upvotes: 0

Peter
Peter

Reputation: 14118

You would have to use the AssemblyQualifiedName. See this article: http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx for more info.

In your case, something like:

MyNamespace.Models.Foo, MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089

The PublicKeyToken could be longer if you've signed your assemblies.

If you're not sure, just create an instance of the object the usual way, and then do:

Type objType = typeof(System.Array);

// Print the full assembly name.
Console.WriteLine ("Full assembly name: {0}.", objType.Assembly.FullName.ToString()); 

// Print the qualified assembly name.
Console.WriteLine ("Qualified assembly name: {0}.", objType.AssemblyQualifiedName.ToString());

(shamelessly nicked from the aforementioned article)

Upvotes: 2

Related Questions