Sometime, we need to create a class with type defined by runtime. These will help.
Below is a helper class
public static class ReflectionHelper
{
/// <summary>
/// Gets a Type of an refed assembly.
/// </summary>
/// <param name="assemblyName">FULL Name of the assembly.</param>
/// <param name="className">FULL Name of the class.</param>
/// <returns></returns>
public static Type GetAssemblyType(string assemblyName, string className)
{
StreamResourceInfo info = Application.GetResourceStream(new Uri(assemblyName, UriKind.Relative));
Assembly assembly = new AssemblyPart().Load(info.Stream);
Type type = assembly.GetType(className);
return type;
}
/// <summary>
/// Gets A type of An RefFed assembly.
/// </summary>
/// <param name="className">FULL Name of the class.</param>
/// <returns></returns>
public static Type GetAssemblyType(string className)
{
Type type = null;
foreach (AssemblyPart part in Deployment.Current.Parts)
{
type = GetAssemblyType(part.Source, className);
if (type != null)
break;
}
return type;
}
}
Next, we use the function
Type loaderType = ReflectionHelper.GetAssemblyType("AssemblyFullName.dll", "AssemblyFullName.ClassName");
object obj = Activator.CreateInstance(loaderType);
//my interface
IToolLoader loader = obj as IToolLoader;
if (loader != null)
{
//use your interface
}
No comments:
Post a Comment