gpt4 book ai didi

c# - 为什么我不能通过 Type.GetType() 找到我在 app.config 中引用的插件实例的类型?

转载 作者:行者123 更新时间:2023-11-30 13:34:53 26 4
gpt4 key购买 nike

所以这是交易。我有我的解决方案,其中有几个项目:

  • 包装器项目 - 这只是一个控制台应用程序,当前在调试期间代表 Windows 服务。
  • 一个工作项目 - 这包含代码的内容。这样我就可以轻松地调试 windows 服务的代码而不会头疼。
  • 一个插件库项目 - 它包含一个插件工厂,用于新建一个插件的具体实例。
  • 一个插件项目 - 这包含我的插件的具体实现。

我的包装器应用程序包含我的 app.config,我的插件应该直接引用它来进行 self 配置。这样,我的包装器应用程序不需要知道任何其他信息,只需调用适配器工厂来更新插件实例。

<configuration>
<appSettings>
<add key="Plugin" value="Prototypes.BensPlugin" />
<add key="Prototypes.BensPlugin.ServiceAddress" value="http://localhost/WebServices/Plugin.asmx" />
<add key="Prototypes.BensPlugin.Username" value="TestUserName" />
<add key="Prototypes.BensPlugin.Password" value="TestPassword" />
</appSettings>
</configuration>

包装项目:

using Worker;

public class Program
{
public static void Main()
{
var serviceProc = new ServiceProcess();
serviceProc.DoYourStuff();
}
}

worker 项目:

using PluginLibrary;

namespace Worker
{
public class ServiceProcess
{
public string GetRequiredAppSetting(string settingName)
{
/* Code to get a required configuration setting */
}

public void DoYourStuff()
{
string pluginTypeName = GetRequiredAppSetting("Plugin");
//At this point, pluginTypeName = "Prototypes.BensPlugin"
Type type = Type.GetType(pluginTypeName); //type == null, wth!?

//string testTypeName = new BensPlugin().GetType().ToString();
///At this point, testTypeName = "Prototypes.BensPlugin"
//Type testType = Type.GetType(testTypeName)
///And testType still equals null!

if (type != null)
{
IPlugin plugin = PluginFactory.CreatePlugin(type);
if (plugin != null)
plugin.DoWork();
}
}
}
}

插件库:

namespace PluginLibrary
{
public interface IPlugin
{
void DoWork();
}

public class PluginFactory
{
public IPlugin CreatePlugin(Type pluginType)
{
return (IPlugin)Activator.CreateInstance(pluginType);
}
}
}

插件:

using PluginLibrary;

namespace Prototypes
{
public class BensPlugin : IPlugin
{
public string ServiceAddress { get; protected set; }
public string username { get; protected set; }
public string password { get; protected set; }

public void DoWork()
{
Trace.WriteLine("Ben's plugin is working.");
}

public BensPlugin()
{
/* Code to self configure from app.config */
}
}
}

好的,到此为止。当我引用 Type.GetType(pluginTypeName) 时,我的工作项目出现了问题。我的 pluginTypeName 已从配置中正确提取,但 Type.GetType(pluginTypeName) 返回 null。我尝试直接在代码中的同一位置更新我的插件实例:

var obj = new BensPlugin();

这工作得很好,obj.GetType().ToString() 返回与我在 app.config 中配置的完全相同的字符串。

谁能告诉我为什么我可以在代码中的那个点新建一个具体对象,但是 Type.GetType(pluginTypeName) 会失败?

最佳答案

可能是您需要指定该类型位于哪个程序集中:

<add key="Plugin" value="Prototypes.BensPlugin, TheAssemblyName" />

关于c# - 为什么我不能通过 Type.GetType() 找到我在 app.config 中引用的插件实例的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1688420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com