Pregunta

After I run my test that runs my suspect code; I cannot rebuild the assembly in Visual Studio until Nunit (or more specifically nunit-agent.exe) is ended.

The error is:

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.

Current workaround is to close nunit, rebuild and then reopen nunit (and then test). painful

The red-herring was thinking this was a Volume Shadow Copy issue or a project base path setting in the nunit project. It is not these. It is this code.

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

I thought this was a disposal problem, so I implemented IDisposable and added the required code to the class "ClassName". Did not work.

How can i fix this problem?

¿Fue útil?

Solución

The solution is to execute

AppDomain.Unload(dom);

Full method:

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);
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top