Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

后端 未结 13 2360
-上瘾入骨i
-上瘾入骨i 2020-11-22 17:21

Is it possible to instantiate an object at runtime if I only have the DLL name and the class name, without adding a reference to the assembly in the project? The class imple

13条回答
  •  鱼传尺愫
    2020-11-22 17:39

    I found this question and some answers very useful, however I did have path problems, so this answer would cover loading library by finding bin directory path.

    First solution:

    string assemblyName = "library.dll";
    string assemblyPath = HttpContext.Current.Server.MapPath("~/bin/" + assemblyName);
    Assembly assembly = Assembly.LoadFrom(assemblyPath);
    Type T = assembly.GetType("Company.Project.Classname");
    Company.Project.Classname instance = (Company.Project.Classname) Activator.CreateInstance(T);
    

    Second solution

    string assemblyName = "library.dll";
    string assemblyPath = HttpContext.Current.Server.MapPath("~/bin/" + assemblyName);
    Assembly assembly = Assembly.LoadFile(assemblyPath);
    (Company.Project.Classname) instance = (Company.Project.Classname) assembly.CreateInstance("Company.Project.Classname");
    

    You can use same principle for interfaces (you would be creating a class but casting to interface), such as:

    (Company.Project.Interfacename) instance = (Company.Project.Interfacename) assembly.CreateInstance("Company.Project.Classname");
    

    This example is for web application but similar could be used for Desktop application, only path is resolved in different way, for example

    Path.GetDirectoryName(Application.ExecutablePath)
    

提交回复
热议问题