C# 加载实现接口的程序集的正确方法?

C# 加载实现接口的程序集的正确方法?,c#,.net,C#,.net,我想这样做: 创建许多实现IMyInterface的程序集 在我的应用程序的web.config或app.config中,定义要加载哪一个(它们可能有不同的名称) 当应用程序启动时,按照web.config中的标记加载程序集,并使用其IMyInterface实现 这样做的最佳方式是什么? 我现在使用的是framework3.5 (另外,我知道我可以定义一个包含程序集名称的变量(例如key=“My assembly”,value=“myassembly.dll”,然后动态加载程序集,只是想知道是否

我想这样做:

  • 创建许多实现IMyInterface的程序集
  • 在我的应用程序的web.config或app.config中,定义要加载哪一个(它们可能有不同的名称)
  • 当应用程序启动时,按照web.config中的标记加载程序集,并使用其IMyInterface实现
  • 这样做的最佳方式是什么? 我现在使用的是framework3.5


    (另外,我知道我可以定义一个包含程序集名称的变量(例如key=“My assembly”,value=“myassembly.dll”,然后动态加载程序集,只是想知道是否有更正确的方法来执行此操作)

    程序集不实现接口;类型实现接口

    对于ASP.NET应用程序,我建议将每个程序集放在
    /bin
    目录中,并使用
    web.config
    配置选项和
    Activator.CreateInstance
    创建实际类型:

    var typeName = "MyNamespace.MyClass, MyAssembly"; // load from config file
    IMyInterface instance = 
                  (IMyInterface)Activator.CreateInstance(Type.GetType(typeName));
    

    程序集不实现接口;类型实现接口

    对于ASP.NET应用程序,我建议将每个程序集放在
    /bin
    目录中,并使用
    web.config
    配置选项和
    Activator.CreateInstance
    创建实际类型:

    var typeName = "MyNamespace.MyClass, MyAssembly"; // load from config file
    IMyInterface instance = 
                  (IMyInterface)Activator.CreateInstance(Type.GetType(typeName));
    
    我这样做如下(我使用基类,用抽象方法代替接口):

    1-列出用我的基类实现的类

    Assembly assembly = null;
    AssemblyName assemblyName = new AssemblyName();
    assemblyName.CodeBase = "FullPathToAssembly";
    
    assembly = Assembly.Load(assemblyName);
    
    
    Type[] arrayTipo;
    arrayTipo = assembly.GetTypes();
    
    var tipos =
    from t in arrayTipo
    where t.BaseType == typeof(DD.Util.BaseProcesso)
    select t;
    
    2-在类的实例中调用执行方法:

    Type tipo = engine.GetType("FullClassName");
    BaseProcesso baseProcesso = (BaseProcesso)Activaor.CreateInstance(tipo, new object[] { "ConstructorParameter1", "ConstructorParameter1") });
    // Event
    baseProcesso.IndicarProgresso += new  BaseProcesso.IndicarProgressoHandler(baseProcesso_IndicarProgresso);
    new Thread(new ThreadStart(baseProcesso.Executar)).Start();
    
    适合我!

    我的做法如下(我使用基类,用抽象方法代替接口):

    1-列出用我的基类实现的类

    Assembly assembly = null;
    AssemblyName assemblyName = new AssemblyName();
    assemblyName.CodeBase = "FullPathToAssembly";
    
    assembly = Assembly.Load(assemblyName);
    
    
    Type[] arrayTipo;
    arrayTipo = assembly.GetTypes();
    
    var tipos =
    from t in arrayTipo
    where t.BaseType == typeof(DD.Util.BaseProcesso)
    select t;
    
    2-在类的实例中调用执行方法:

    Type tipo = engine.GetType("FullClassName");
    BaseProcesso baseProcesso = (BaseProcesso)Activaor.CreateInstance(tipo, new object[] { "ConstructorParameter1", "ConstructorParameter1") });
    // Event
    baseProcesso.IndicarProgresso += new  BaseProcesso.IndicarProgressoHandler(baseProcesso_IndicarProgresso);
    new Thread(new ThreadStart(baseProcesso.Executar)).Start();
    
    为我工作