我創建了一個測試庫影子拷貝,以不鎖組件
public class Test
{
public int Add(int val1, int val2)
{
return val1 + val2;
}
}
一個項目來調用它:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
namespace Loader
{
class Program
{
static void Main(string[] args)
{
String path = @"...Lib.dll"; // path to lib
var name = Path.GetFileName(path);
AppDomainSetup setup = new AppDomainSetup
{
ApplicationBase = @"...", // directory where Lib.dll is
ShadowCopyFiles = "true",
ShadowCopyDirectories = @"..."// directory where Lib.dll is
};
var appdomain = AppDomain.CreateDomain("Loader." + name, null, setup);
Assembly ass = Assembly.LoadFile(path); // <--- I think here is the problem, here where assembly is locked
Assembly assembly = appdomain.Load(ass.FullName);
dynamic a = assembly.CreateInstance("Lib.Test");
Console.WriteLine(a.Add(1, 5));
}
}
}
請幫忙找一下我做錯了?爲什麼我的程序集被鎖定?
編輯:用硬編碼集名稱:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
namespace Loader
{
class Program
{
static void Main(string[] args)
{
AppDomainSetup ads = new AppDomainSetup();
String fullPath = @"c:\users\myuser\documents\visual studio 2010\Projects\ShadowCopy\Loader\bin\Debug\Lib.dll";
ads.ShadowCopyFiles = "true";
ads.ApplicationName = "AppName";
ads.ShadowCopyDirectories = Path.GetDirectoryName(fullPath);
//ads.ApplicationBase = Path.GetDirectoryName(fullPath);
//ads.PrivateBinPath = Path.GetDirectoryName(fullPath);
ads.CachePath = @"c:\users\myuser\documents\visual studio 2010\Projects\ShadowCopy\Loader\bin\Debug\Cache\";
AppDomain ad = AppDomain.CreateDomain("myName" + ads.ApplicationName, null, ads);
ad.AssemblyResolve += new ResolveEventHandler(ad_AssemblyResolve);
Console.WriteLine(ad.ShadowCopyFiles);
Console.WriteLine(ad.SetupInformation.ShadowCopyDirectories);
try
{
//Assembly assembly = ad.Load(AssemblyName.GetAssemblyName(fullPath));
//dynamic obj = ad.CreateInstanceAndUnwrap(assembly.GetName().Name, "Lib.Test");
dynamic obj = ad.CreateInstanceAndUnwrap("Lib", "Lib.Test");
Console.WriteLine(obj.Add(1, 7));
Console.ReadKey();
Console.WriteLine(obj.Add(1, 90));
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
static Assembly ad_AssemblyResolve(object sender, ResolveEventArgs args)
{
return Assembly.LoadFile(@"c:\users\myuser\documents\visual studio 2010\Projects\ShadowCopy\Loader\bin\Debug\Lib.dll");
}
}
}
有趣的是,緩存assebly也被鎖定。
編輯2:
這裏是代碼行阻擋組件
Console.WriteLine(obj.Add(1, 7));
因此,一旦在Lib.Test的方法訪問的assenbly被阻止。
什麼是解決方案?
請發佈您正在獲取的確切錯誤。 –
我說過的確切問題是Lib。dll程序集被鎖定。 例如,一旦應用程序正在運行,我無法回報它。 – NDeveloper
您需要在第三個程序集中使用接口,以防止代碼將構造類型加載到主AppDomain中。不要使用LoadFile。 –