samedi 21 avril 2018

C# - Load Type from Custom Assembly

I'm writing a C# application that might reference class library that I'm also writing. The class library is intended to be a template for other class libraries I might want to use. My intention, is to dynamically load and use a type from the assembly generated by the class library. I want to load the type based on a configurable setting. At this time, my setting looks like this:

"MyOrg.MyApp.Services.Example, MyOrg.MyApp.Services"

What this string means is that I want to use the Example class in the MyOrg.MyApp.Services namespace, which comes from MyOrg.MyApp.Services.dll. I based this setting format on the type property that's used in the section element for a custom config section in an app.config file as shown here.

My question is, how do I load this assembly and actually get an instance of the Example class from this string? At this time, I have:

Assembly assembly = Assembly.Load("MyOrg.MyApp.Services.Example, MyOrg.MyApp.Services");

However, when I run that, I receive the following error:

Could not load file or assembly 'MyOrg.MyApp.Services.Example\, MyOrg.MyApp.Services' or one of its dependencies. The given assembly name or codebase was invalid.

I know the problem is because a type is named in my string. If I just use MyOrg.MyApp.Service", the assembly loads fine. However, I don't see a way to load the Example type.

Is there a utility method that I'm overlooking that will allow me to do this? If not, how do I load a specific type from a custom assembly? Thank you!





Aucun commentaire:

Enregistrer un commentaire