Activator.CreateInstance causing nunit to lock which prevents visual studio building

帅比萌擦擦* 提交于 2019-12-24 01:19:00

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/13003806/activator-createinstance-causing-nunit-to-lock-which-prevents-visual-studio-buil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!