No1、本Demo 定义了一个接口IserviceToolFrame,接口中有一个方法Run。
No2、在另外两个工程中,分别定义两个类serviceToolCatComplete、serviceToolDogComplete实现接口IserviceToolFrame。
No3、控制台程序通过动态加载Dll的方式去调用IserviceToolFrame的实例,输出不同的内容。代码如下:
动态加载Dll方法
csharp
public void Main()
{
Console.WriteLine($"框架启动");
Dictionary<string, string> AllDll = new Dictionary<string, string>();
AllDll.Add("serviceToolCat.serviceToolCatComplete", "E:\\work\\codes\\1NetCore\\serviceTool\\serviceToolTest\\complete\\serviceToolCat\\bin\\Debug\\net6.0\\serviceToolCat.dll");
AllDll.Add("serviceToolDog.serviceToolDogComplete", "E:\\work\\codes\\1NetCore\\serviceTool\\serviceToolTest\\complete\\serviceToolDog\\bin\\Debug\\net6.0\\serviceToolDog.dll");
//实现方式一
foreach (var d in AllDll)
{
Task.Run(() =>
{
System.Reflection.Assembly assembly = Assembly.LoadFile(d.Value);
IServiceToolDo itool = assembly.CreateInstance(d.Key) as IServiceToolDo;
itool.Run();
});
}
//实现方式二
foreach (var d in AllDll)
{
Task.Run(() =>
{
System.Reflection.Assembly assembly = Assembly.LoadFile(d.Value);
foreach (var t in assembly.GetTypes())
{
Console.WriteLine(t.Name);
MethodInfo m = t.GetMethod("Run");
Console.WriteLine(m.Name);
m.Invoke(assembly.CreateInstance(d.Key), null);
}
});
}
}
输出效果如图:
接口定义
csharp
namespace serviceToolFrame
{
public interface IServiceToolDo
{
public void Run() { Console.WriteLine("接口未能实现"); }
}
}
Dog类实现
csharp
public class serviceToolDogComplete : IServiceToolDo
{
public void Run()
{
while (true)
{
Console.WriteLine($"{DateTime.Now} {Environment.NewLine} Dog Dog .......");
System.Threading.Thread.Sleep(5000);
}
}
}
Cat类实现
csharp
public class serviceToolCatComplete: IServiceToolDo
{
public void Run()
{
while (true)
{
Console.WriteLine($"{DateTime.Now} {Environment.NewLine} Cat Cat .......");
System.Threading.Thread.Sleep(15000);
}
}
}