Activator.CreateInstance导致nunit锁定,阻止视觉工作室建设

时间:2012-10-22 01:07:25

标签: c# visual-studio-2010 activator

运行我运行可疑代码的测试后;在Nunit(或更具体地说是nunit-agent.exe)结束之前,我无法在Visual Studio中重建程序集。

错误是:

Could not copy "C:\path\MyTests\MyTests.dll" to "bin\Debug\MyTests.dll". 
    Exceeded retry count of 10.
Unable to copy file "C:\path\MyTests\Debug\MyTests.dll" 
    to "bin\Debug\MyTests.dll". The process cannot access the file 
    'bin\Debug\MyTests.dll' because it is being used by another process.

目前的解决方法是关闭nunit,重建然后重新打开nunit(然后测试)。 痛苦

红鲱鱼认为这是nunit项目中的卷影复制问题或项目基本路径设置。不是这些。这是代码。

AppDomain dom = AppDomain.CreateDomain("some");
string fullPath = Assembly.GetExecutingAssembly().CodeBase
                  .Replace("file:///", "").Replace("/", "\\");
AssemblyName assemblyName = new AssemblyName();
assemblyName.CodeBase = fullPath;
Assembly assembly = dom.Load(assemblyName);
Type type = assembly.GetType("ClassName");

IMyInterface obj = Activator.CreateInstance(type) as IMyInterface;

obj.ActionMessage(param1, param2);

我认为这是一个处理问题,因此我实现了IDisposable并将所需的代码添加到“ClassName”类中。没用。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

解决方案是执行

AppDomain.Unload(dom);

完整方法:

public static object InstObject(Assembly ass, string className)
{
    AppDomain dom = null;
    try
    {
        Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);

        string fullPath = ass.CodeBase.Replace("file:///", "").Replace("/", "\\");
        AssemblyName assemblyName = new AssemblyName();
        assemblyName.CodeBase = fullPath;
        dom = AppDomain.CreateDomain("TestDomain", evidence, 
                 AppDomain.CurrentDomain.BaseDirectory, 
                 System.IO.Path.GetFullPath(fullPath), true);

        Assembly assembly = dom.Load(assemblyName);
        Type type = assembly.GetType(className);

        object obj = Activator.CreateInstance(type);

        return obj;
    }
    finally
    {
        if (dom != null) AppDomain.Unload(dom);
    }
}