【问题标题】:Is this plugin framework IoC/DI?这个插件框架是 IoC/DI 吗?
【发布时间】:2011-09-26 14:47:11
【问题描述】:

我正在为我的 ASP.NET C# 应用程序开发一种方法,以便在安装新插件时无需重新编译主机应用程序即可使用插件。

这是我的插件加载器类(基于在线找到的教程。)

public class PluginLoader
{
    public static IList<IPlugin> Load(string folder)
    {
        IList<IPlugin> plugins = new List<IPlugin>();

        // Get files in folder
        string[] files = Directory.GetFiles(folder, "*.plug.dll");
        foreach(string file in files)
        {
            Assembly assembly = Assembly.LoadFile(file);
            var types = assembly.GetExportedTypes();
            foreach (Type type in types)
            {
                if (type.GetInterfaces().Contains(typeof(IPlugin)))
                {
                    object instance = Activator.CreateInstance(type);
                    plugins.Add(instance as IPlugin);
                }
            }
        }
        return plugins;
    }
}

这个概念是在主机应用程序中创建一个新插件可以使用的 IPlugin 接口。然后加载程序搜索可用的 DLL 并找到 IPlugin 类型的类。然后将它们实例化,我的主机应用程序可以按照它认为合适的方式使用它们。

例如它可以这样做:

protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        string folder = Server.MapPath("~/bin/");
        path.Text = folder;

        var plugins = PluginLoader.Load(folder);
        if (plugins.Count == 0)
            sb.Append("No plugins found");
        else
        {
            sb.Append("<ul>");
            foreach (var plug in plugins)
            {

                sb.AppendFormat("<li>Default: {0}</li>", plug.Label);
                plug.SetLabel("Overwrote default label.");
                sb.AppendFormat("<li>New: {0}</li>", plug.Label);
            }
            sb.Append("</ul>");
        }

        message.Text = sb.ToString();
    }

这个结构是 IoC 还是 DI?该插件正在引用主机,而不是相反。这似乎与控制反转的概念一致。这段代码和 IoC/DI 有根本区别吗?

【问题讨论】:

  • 看起来更像是服务定位器模式而不是 IoC 模式。 IoC 的发明是为了避免使用服务定位器。

标签: c# plugins dependency-injection inversion-of-control


【解决方案1】:

这看起来像一个使用控制反转但不使用依赖注入的插件架构。它似乎类似于 MEF 的工作方式。

【讨论】:

    【解决方案2】:

    同意理查德的回答。我认为你最终会成为一个基本的服务定位器。 DI 容器将根据容器中的其他类型提供类型的实际自动实例化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      相关资源
      最近更新 更多