Activator.CreateInstance causes a nunit lock, which prevents visual studio building

After running my test, which runs my suspicious code; I cannot rebuild the assembly in Visual Studio until Nunit (or, more specifically, nunit-agent.exe) finishes.

Error:

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. 

The current workaround is to close nunit, rebuild, and then open nunit again (and then check). painful

Red-herring thought this was a problem with a copy of the volume volume or the base path to the project in the nunit project. It is not they. This is the 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 removal problem, so I implemented IDisposable and added the required code to the ClassName class. Does not work.

How can I fix this problem?

+2
source share
1 answer

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

Source: https://habr.com/ru/post/891470/


All Articles