Reflection: Get Type by string & instance class from another assembly

Hi everyone! Today I talk you about reflection and create instance by type.
Business scenario:

We have a dll called: Integra.Communicator.Zk.dll. This dll has many methods and classes but we have to interest in the class CommunicatorApi that implement the ICommunicator Interface. We want to use GetUsers() method of this class.
We have a restriction we don’t want to instance directly CommunicatorApi Class, we need to use only the Interface, and we want to instance the class by type name (string).

The first step is get the type from typeName

Type communicatorType = Type.GetType(typeName);

The typeName is a assembly qualified name of the type to get. In others words: namespaces.className , assemblyName.
In our case: “Integra.Communicator.Zk.CommunicatorApi,Integra.Communicator.Zk”

Integra.Communicator.Zk.CommunicatorApi : Communicator Class that implement the ICommunicator Interface

Integra.Communicator.Zk : Assembly name that content the communicator class.

Second step is instance the class:

 Class/Interface instance = Activator.CreateInstance(TYPE, parameters) as Class/Interface;

Ok, we have already many theoric. Let’s code:

We want to list the users. The first step is pass the typeName to the CommunicatorService, then the service return us the ICommunicator Interface and finally we can list the users:

In the service:
1) Get type from type name ( assembly qualified name – namespace.className, assembleName)
2) We use Activator.CreateInstance with this Type and we create a new CommunicatorApi Instance.
This CommunicatorApi class implement ICommunicator interface and has only a constructor that receive ConnectionParameters instance as a parameter. This parameter has ip and port properties,

Finally, we can show the results:

Resume:
We accessed to classes that live in another assembly.
We were able to instance clases from a “typeName”, when we says “typeName” we’re speaking about “namespaces.className, assemblyName”.

Github repo:
https://github.com/morales-franco/JungleApp

See you later!