其實(shí)主要是利用類特性,來(lái)存儲(chǔ)程序集信息,在利用反射創(chuàng)建實(shí)例唬血。與將程序集信息寫(xiě)在配置文件里效果一樣响逢。
首先新建特性類绒窑,繼承Attribute
<pre>
public class DLLInfoAttribute:Attribute
{
public string DllName { get; set; }
public string FullClassName { get; set; }
}
</pre>
我們新建一個(gè)接口,抽象業(yè)務(wù)邏輯舔亭。
<pre>
[DLLInfo(DllName = "BLL.dll", FullClassName = "BLL.ClassA")]
public interface IClassA
{
int Add();
}
</pre>
在接口上添加特性信息些膨,DLLName是業(yè)務(wù)邏輯實(shí)例的dll文件名稱,F(xiàn)ullClassName是命名空間+類名钦铺。
然后我們新增業(yè)務(wù)邏輯類订雾,繼承接口IClassA
<pre>
namespace BLL
{
public class ClassA:IClassA
{
public int Add()
{
return 0;
}
}
}
</pre>
UI層引用IClass接口項(xiàng)目,DllInfo特性類項(xiàng)目矛洞。
調(diào)用方法如下
<pre>
private void button_Click(object sender, EventArgs e)
{
IClassA ca = (IClassA)CreateInstance(typeof(IClassA), typeof(DLLInfoAttribute));
ca.Add();
}
private object CreateInstance(Type t, Type attri)
{
object[] obj = t.GetCustomAttributes(attri, true);
DLLInfoAttribute dllInfoC = (DLLInfoAttribute)obj[0];
System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(Application.StartupPath + "\\" + dllInfoC.DllName);
return assembly.CreateInstance(dllInfoC.FullClassName);
}
</pre>
這樣洼哎,實(shí)現(xiàn)了UI層與業(yè)務(wù)邏輯層解耦。