所以这就是交易。我有我的解决方案,其中有几个项目:
- 包装器项目 - 这只是一个控制台应用程序,当前在调试期间代表 Windows 服务。
- 一个工作者项目——包含代码的核心内容。这样我就可以轻松地调试 Windows 服务的代码,而不用头疼。
- 插件库项目 - 这包含一个插件工厂来新建插件的具体实例。
- 一个插件项目 - 这包含我的插件的具体实现。
我的包装应用程序包含我的 app.config,我的插件应直接引用它以进行自我配置。这样,我的包装应用程序不需要知道任何其他信息,只需调用适配器工厂来更新插件的实例即可。
<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();
}
}
工人项目:
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);
}
}
}
Plugin:
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)
. My pluginTypeName
正在从配置中正确提取,但是Type.GetType(pluginTypeName)
回报null
。我尝试直接在代码中的同一位置更新插件的实例:
var obj = new BensPlugin();
这工作得很好,而且obj.GetType().ToString()
返回与我在中配置的完全相同的字符串app.config
.
谁能告诉我为什么我可以在代码中的那个位置新建一个具体对象,但是Type.GetType(pluginTypeName)
会失败吗?