Skip to main content
 首页 » 编程设计

c#之Activator.CreateInstance 导致 nunit 锁定,从而阻止 visual studio 构建

2024年01月01日32cyq1162

在我运行运行可疑代码的测试之后;在 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”中。没用。

我该如何解决这个问题?

请您参考如下方法:

解决方案是执行

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); 
    } 
}