从不同的程序集动态加载类(具有自定义行为)?

时间:2013-02-28 18:27:51

标签: c# .net dynamic-loading

我们正在为少数客户构建应用程序,每个客户都有自己的要求以及类似的要求。我们还希望将所有代码保存在同一个应用程序中,而不是将其分支,并且IF不是很好的选择,因为它将遍布各地。

我计划为所有人提供基础课程。然后每个客户都有自己的类,其中override方法将执行特殊逻辑。

我们如何在编译时加载程序集而不是执行此操作

public class BaseClass {
    public string getEventId()
}

public class ClassForJohn:BaseClass {
    [override]
    public string getEventId()
}

public class ClassForAdam:BaseClass {
    [override]
    public string getEventId()
}

void UglyBranchingLogicSomewhere() {
   BaseClass  eventOject;
   if("John"==ConfigurationManager.AppSettings["CustomerName"]){
        eventOject = new ClassForJohn();


   }else if("Adam"==ConfigurationManager.AppSettings["CustomerName"]){
        eventOject = new ClassForAdam();


   }else{
        eventOject = new BaseClass ();

   }
  eventId = eventOject.getEventId();
}

6 个答案:

答案 0 :(得分:6)

这就是我将插件(加载项)加载到我的一个项目中的方式:

const string PluginTypeName = "MyCompany.MyProject.Contracts.IMyPlugin";

/// <summary>Loads all plugins from a DLL file.</summary>
/// <param name="fileName">The filename of a DLL, e.g. "C:\Prog\MyApp\MyPlugIn.dll"</param>
/// <returns>A list of plugin objects.</returns>
/// <remarks>One DLL can contain several types which implement `IMyPlugin`.</remarks>
public List<IMyPlugin> LoadPluginsFromFile(string fileName)
{
    Assembly asm;
    IMyPlugin plugin;
    List<IMyPlugin> plugins;
    Type tInterface;

    plugins = new List<IMyPlugin>();
    asm = Assembly.LoadFrom(fileName);
    foreach (Type t in asm.GetExportedTypes()) {
        tInterface = t.GetInterface(PluginTypeName);
        if (tInterface != null && (t.Attributes & TypeAttributes.Abstract) !=
            TypeAttributes.Abstract) {

            plugin = (IMyPlugin)Activator.CreateInstance(t);
            plugins.Add(plugin);
        }
    }
    return plugins;
}

我假设每个插件都实现了IMyPlugin。您可以以任何方式定义此接口。如果循环遍历插件文件夹中包含的所有DLL并调用此方法,则可以自动加载所有可用的插件。

通常你至少有三个程序集:一个包含接口定义,一个引用这个接口程序集的主程序集,以及至少一个实现(当然还引用)这个接口的程序集。

答案 1 :(得分:4)

每个客户是否都有自己的exe和配置文件,并且有共享的dll?或者是否有共享的exe,每个客户都有自己的dll?

您可以在配置中输入完整的类型名称:

Shared.exe.config:

<appSettings>
  <add key="CustomerType" value="NamespaceForJohn.ClassForJohn, AssemblyForJohn"/>
</appSettings>

AssemblyForJohn.dll 放在与 Shared.exe 相同的文件夹中。

然后你可以在这样的代码中动态加载它:

Shared.exe:

var typeString = ConfigurationManager.AppSettings["CustomerType"];
var parts = typeString.Split(',');
var typeName = parts[0];
var assemblyName = parts[1];
var instance = (BaseClass)Activator.CreateInstance(assemblyName, typeName).Unwrap();

答案 2 :(得分:2)

也许这个例子会有所帮助

public MyInterface GetNewType() { 
       Type type = Type.GetType( "MyClass", true ); 
       object newInstance = Activator.CreateInstance( type ); 
       return newInstance as MyInterface; 
    } 

答案 3 :(得分:1)

以下是使用Unity进行DI处理的一种方法。

IUnityContainer container = new UnityContainer();
string customerNamespace = ConfigurationManager.AppSettings["CustomerNamespace"];
container.RegisterType(typeof(ISomeInterface), 
                       Type.GetType(customerNamespace+".SomeImplementation"));


// ...

ISomeInterface instance = conainer.Resolve<ISomeInterface>();

每个客户在客户特定的命名空间中都有自己的ISomeInterface实现。

答案 4 :(得分:1)

您可以通过以下方式从程序集创建外部类型的实例:

object obj = Activator.CreateInstance( 
    "External.Assembly.Name", "External.Assembly.Name.TypeName");
BaseClass b = (BaseClass) obj;
b.getEventId();

您将存储程序集的名称并键入配置文件或其他适当的位置。

答案 5 :(得分:0)

我会使用Unity,但作为简单工厂。

Unity Framework: How to Instantiate two classes from the same Interface?

您可以存储

我正在使用Unity.2.1.505.2(以防万一有所不同)。

  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>


      <unity>
        <container>
          <register type="IVehicle" mapTo="Car" name="myCarKey" />
          <register type="IVehicle" mapTo="Truck" name="myTruckKey" />
        </container>
      </unity>

这是DotNet代码。

UnityContainer container = new UnityContainer();

UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                section.Configure(container);

string myKey = "John";  /* read from config file */ /* with this example, the value should be "myCarKey" or "myTruckKey"  */

IVehicle v1 = container.Resolve<IVehicle>(myKey); 

请参阅:

http://msdn.microsoft.com/en-us/library/ff664762(v=pandp.50).aspx

http://www.sharpfellows.com/post/Unity-IoC-Container-.aspx