简体   繁体   中英

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?

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)

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);

Type.GetType argument is AssemblyQualifiedName: from MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM