跨多个程序集实现部分方法

Bil*_*ill 7 c# asp.net

在我正在开发的其中一个应用程序中,包括两个基本功能:创建和更新.

但是,有时需要添加自定义代码,所以我想通过允许第三方编写和嵌入自己的代码来扩展代码:

OnCreating OnCreated OnUpdating OnUpdated

有没有办法在多个程序集中启用上述功能?MEF可能会有帮助吗?

谢谢你


谢谢大家的回复.

具有这样的接口意味着每个外部组件必须根据需要实现该接口.然后,我的应用程序的代码需要遍历当前运行的程序集,检测实现该接口的所有类,并运行它们的方法?

MEF适合这里吗?我可以从外部程序集导出实现并将其导入我的应用程序中?

谢谢你

Cod*_*aos 14

您不能在程序集中使用粒子类,因为部分类是语言功能,而不是CLR功能.C#编译器将所有的部分类合并为一个真正的类,并且该单个类是编译后唯一剩下的部分.

你有几个选择:

  1. 提供活动
  2. 使方法成为虚拟并覆盖它们
  3. 使用界面

您的问题看起来最适合事件.用户可以在其他程序集中简单地订阅它们.


Jam*_*des 2

关于您的 MEF 问题,您可能可以执行以下操作来从接口运行方法:

var catalog = new DirectoryCatalog("bin");
var container = new CompositionContainer(catalog);
container.ComposeParts();

var plugins = container.GetExportedValues<IPlugin>();
foreach (IPlugin plugin in plugins)
{
    plugin.OnCreating();
}
Run Code Online (Sandbox Code Playgroud)

或者按照 Brian Mains 的建议创建一个包含事件的界面:

public interface IPlugin 
{
    event OnCreatingEventHandler OnCreating;
}
Run Code Online (Sandbox Code Playgroud)

那么上面的代码会更像:

var catalog = new DirectoryCatalog("bin");
var container = new CompositionContainer(catalog);
container.ComposeParts();

var plugins = container.GetExportedValues<IPlugin>();
foreach (IPlugin plugin in plugins)
{
    plugin.OnCreating += MyOnCreatingHandler;
}
Run Code Online (Sandbox Code Playgroud)

我想我喜欢后者作为您指定的方法名称。对于我的插件工作,我创建了一个类似于以下内容的界面:

public interface IPlugin
{
    void Setup();
    void RegisterEntities();
    void SeedFactoryData();
}
Run Code Online (Sandbox Code Playgroud)

RegisterEntities()方法在运行时扩展数据库模式,并且该SeedFactoryData()方法添加任何默认数据(例如添加默认用户、预填充城市表等)。