我做了一个网站为A,这个网站单独运行没有问题;我现在又新建了一个网站B,我现在需要将这个B网站当成一个应用插件加到A中,所以,我就将网站B的相关文件(比如就只有一个default.aspx)放到网站A的APPS目录下(比如<Apps/B/default.aspx),然后将B网站的Bin目录下的dll也拷贝到APPS的B目录下(Apps/B/Lib/b.dll),然后我再A的global.asax的application_start里面加载B的dll文件。但是却总是报错“ 未能加载类型“Plugs.Application.Default”。代码如下:
- C# code
void Application_Start(object sender, EventArgs e) { //在应用程序启动时运行的代码 Framework.PlugsHostService.Instance.LoadPlugs(); }-------------private bool alreadyLoad = false;//查找所有的插件的路径 private static List<string> FindPlugin() { List<string> PluginPaths = new List<string>(); try { //获取当前程序的启动路径 string path = appLocation; //合并路径,指向插件所在的目录 path = Path.Combine(path, "Lib"); string[] fileNames = Directory.GetFiles(path, "*.dll"); foreach (string fileName in fileNames) { PluginPaths.Add(fileName); } } catch (Exception exp) { throw exp; } return PluginPaths; }public void LoadPlugs() { if (alreadyLoad) { return; } List<string> PluginPaths = FindPlugin(); PluginPaths = DeleteInvalidPlugin(PluginPaths); foreach (string path in PluginPaths) { try { //获得 文件名称 string asmFile = path; string asmName = System.IO.Path.GetFileNameWithoutExtension(asmFile); if (asmFile != string.Empty) { // 利用反射,构造DLL文件的实例 System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFile(asmFile); Type[] t = asm.GetExportedTypes(); foreach (Type type in t) { if (type.GetInterface(typeof(IPlugs).FullName) != null) { IPlugs iPlugs = (IPlugs)System.Activator.CreateInstance(type); // 在主程序中使用这个类的实例 //AppDomain.CurrentDomain.Load(asm.GetName()); //AppDomain.CurrentDomain.ExecuteAssembly(asmFile);//.ExecuteAssembly(asmFile); AppDomain.CurrentDomain.Load(asm.FullName, AppDomain.CurrentDomain.Evidence); //调试时,到这里就报错 } } } alreadyLoad = true; } catch (Exception ex) { throw ex; } } }
------解决方案--------------------------------------------------------
反射?
public void test1()
{
System.Reflection.Assembly ass;
Type type ;
object obj;
try
{
ass = System.Reflection.Assembly.LoadFile(@"d:TestReflect.dll"); //要读取的dll路径
type = ass.GetType("Webtest.ReflectTest");
//必须使用名称空间+类名称(如果又空间名) ReflectTest 为类名
System.Reflection.MethodInfo method = type.GetMethod("WriteString"); //方法的名称
obj = ass.CreateInstance("Webtest.ReflectTest"); //必须使用名称空间+类名称
string s = (string)method.Invoke(obj,new string[]{"jianglijun"}); //实例方法的调用
Response.Write(s+" ");
method = type.GetMethod("WriteName"); //方法的名称
s = (string)method.Invoke(null,new string[]{"jianglijun"}); //静态方法的调用