简体   繁体   中英

How to get the Type of a class in Main Project through a class in Class Library Project

I have a class library project which is attached to a main project and in this class library project I have a class named SQSQueueScheduler.cs under this class I have written the below code

Contacts contact = (Contacts)ConfigurationManager.GetSection("bolteContactConfiguration");
 if (contact != null)
        {
            className = contact.ClassName;
            Type myclass = Type.GetType(className);
            objContacts = (Contacts)Activator.CreateInstance(myclass);
        }

The Contacts here is a base class through which I want to create the instnace of derived class ChildContacts dynamically. This base class is present in class library project and the derived class in main website. The value of variable className is Child.ChildContacts(AIST is the namespace and AISTContacts is the name of class). Here I am getting the Null value in myClass variable. The code I have written in web.config of the main project is

<section name="bolteContactConfiguration" type="TDNBolte.Contacts,3DN Bolte" requirePermission="false"/>
<bolteContactConfiguration name ="Contacts" className="Child.ChildContacts"/>

Here 3DN Bolte is the name of assembly of class library project.

I would like to ask, is there a way to get the type of class present in main website(ChildContacts) through the code written in a class(SQSQueueScheduler) of class library project?

The particular overload of GetType that you're using states:

If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

But the type that you're trying to load is neither in Mscorlib.dll nor in the current assembly. So you need to supply an assembly qualified name. Something like Child.ChildContacts, MainProject.dll (assuming the assembly is not strong named).

But note my comments that you probably ought to instead have the main project supplying configuration or factory methods explicitly to the class library 1 so that it's not trying to pull apart the consuming application via reflection.


1 Or embrace Dependency Injection 2 and design your class library to assume the presence of one. Then simply list it as a requirement for use of your class library that a suitable Contacts implementation is registered in the container.

2 Eg Dependency injection in ASP.Net Core

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