C#動態載入DLL,通過設定檔實現對程式集的隨插即用
大概介紹下思想和使用的技術
1,需要載入的dll均為一個類庫
2,每個類均實現一個介面(即這些類有相同的共有方法)
3,使用xml設定檔
4,自動同步最新的xml檔案
5,使用dictionary
實現邏輯
1,程式開始運行後,載入初始的所有任務
2,根據每個任務,建立相應的對象,並把這些對象儲存在dictionary中
3,當使用者請求一個任務時候,去dictionary中根據任務名稱(dictionary的key)找到相應的類
4,調用該類執行相應的方法
5,若需要新的任務(此任務不包含在任務dictionary中),只需要更新xml檔案,程式會重讀xml檔案載入最新的任務到dictionary中,保證程式在運行狀態可以增減新的任務。
class Program
{
static void Main(string[] args)
{
Dictionary<string, IBaseJob> runningJobList = GetJobList();
Console.ForegroundColor = ConsoleColor.Green;
Show(" Please input the job name which you want to do,\r\n Input 'C' can get the last version job.");
Console.ResetColor();
while (true)
{
try
{
string content = Console.ReadLine().ToLower();
if (content.ToLower() == "c")
{
Console.ForegroundColor = ConsoleColor.Magenta;
Show("Compare Started,Job count: " + runningJobList.Count);
runningJobList = GetJobList();
Show("Compare Completed,Job count: " + runningJobList.Count);
Console.ResetColor();
}
else
{
if (content.Length >= 2)
{
DoJob(content, runningJobList, new Random().Next());
}
}
}
catch (Exception e)
{
Show(e.Message);
}
Thread.Sleep(1000);
}
}
static Dictionary<string, IBaseJob> GetJobList()
{
Dictionary<string, string> dictJobs = LoadXML();
Dictionary<string, IBaseJob> jobList = new Dictionary<string, IBaseJob>();
IBaseJob baseJob = null;
foreach (string key in dictJobs.Keys)
{
baseJob = LoadAssembly(key, dictJobs[key]);
if (baseJob != null)
{
jobList.Add(key.Replace("JobProvider", "").ToLower(), baseJob);
}
}
return jobList;
}
static Dictionary<string, string> LoadXML()
{
Dictionary<string, string> dictJobs = new Dictionary<string, string>();
XmlDocument xml = new XmlDocument();
xml.Load("ProviderConfig.xml");
XmlNodeList xmlList = xml.SelectNodes("ProviderInformation");
foreach (XmlNode node in xmlList)
{
XmlNodeList childNodes = node.ChildNodes;
foreach (XmlNode childNode in childNodes)
{
dictJobs.Add(childNode.ChildNodes[0].InnerXml, childNode.ChildNodes[1].InnerXml);
}
}
return dictJobs;
}
static IBaseJob LoadAssembly(string ddlName, string className)
{
IBaseJob baseJob = null;
Assembly jobAssembly = null;
jobAssembly = Assembly.Load(ddlName);
if (jobAssembly != null)
{
object tmpobj = jobAssembly.CreateInstance(className);
if (tmpobj != null && tmpobj is IBaseJob)
{
baseJob = tmpobj as IBaseJob;
}
}
return baseJob;
}
static void DoJob(string key, Dictionary<string, IBaseJob> runningJobList, object objPara)
{
try
{
Console.ForegroundColor = ConsoleColor.Cyan;
Show(runningJobList[key].DoTempJob(objPara).ToString());
Console.ResetColor();
}
catch (KeyNotFoundException)
{
Console.ForegroundColor = ConsoleColor.Red;
Show("The job '" + key + "' you want not exsit in job list.");
Console.ResetColor();
}
catch (Exception e)
{
throw e;
}
}
static void Show(string information)
{
Console.WriteLine(information);
}
}
代碼下載