Loading DLLs into a separate AppDomain with known only common interface - c#

I need to load .dll(plugins) in another domain. In main app I don't know anything about plugins types, only that they implement common interface ICommonInterface with some methods. So this code wouldn't help, because I can't create an instance with interface type.
AppDomain domain = AppDomain.CreateDomain("New domain name");
//Do other things to the domain like set the security policy
string pathToDll = #"C:\myDll.dll"; //Full path to dll you want to load
Type t = typeof(TypeIWantToLoad);
TypeIWantToLoad myObject = (TypeIWantToLoad)domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName);
My question is how I can load assembly in new domain and get the instance, if I know only interface name which implements type I want to create.
UPDATE:
Here is my code:
MainLib.dll
namespace MainLib
{
public interface ICommonInterface
{
void ShowDllName();
}
}
PluginWithOutException.dll
namespace PluginWithOutException
{
public class WithOutException : MarshalByRefObject, ICommonInterface
{
public void ShowDllName()
{
Console.WriteLine("PluginWithOutException");
}
}
}
PluginWithException.dll
namespace PluginWithException
{
public class WithException : MarshalByRefObject, ICommonInterface
{
public void ShowDllName()
{
Console.WriteLine("WithException");
throw new NotImplementedException();
}
}
}
And main application:
static void Main(string[] args)
{
string path = #"E:\Plugins\";
string[] assemblies = Directory.GetFiles(path);
List<string> plugins = SearchPlugins(assemblies);
foreach (string item in plugins)
{
CreateDomainAndLoadAssebly(item);
}
Console.ReadKey();
}
public static List<string> SearchPlugins(string[] names)
{
AppDomain domain = AppDomain.CreateDomain("tmpDomain");
domain.Load(Assembly.LoadFrom(#"E:\Plugins\MainLib.dll").FullName);
List<string> plugins = new List<string>();
foreach (string asm in names)
{
Assembly loadedAssembly = domain.Load(Assembly.LoadFrom(asm).FullName);
var theClassTypes = from t in loadedAssembly.GetTypes()
where t.IsClass &&
(t.GetInterface("ICommonInterface") != null)
select t;
if (theClassTypes.Count() > 0)
{
plugins.Add(asm);
}
}
AppDomain.Unload(domain);
return plugins;
}
Plugins and main app have reference to MainLib.dll. The main aim is to not to load assemblies in default domain, but load them to another domains, so when I don't need them, I just Unload() domain and unload all plugins from application.
For now the exception is FileNotFoundException, Could not load file or assembly 'PluginWithException, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.) on string Assembly loadedAssembly = domain.Load(Assembly.LoadFrom(asm).FullName);(I trying to load plugin with name PluginWithException), I've delete all the dependencies in plugins, exept System, I loaded System.dll in this domain(it loaded correct and it is in domain), but still cant load plugins into domain. Also I checked, that PluginWithException has 2 dependencies - mscorlib and MainLib, and all of them loaded to this domain.
UPDATE: Here I asked this question with more details.

I'm not sure if it's what you need, i'd try to help you with this.
This is how I do to load plugin assemblies. I use a helper class to manage new AppDomain and the instance of the class on that assembly. This is the helper class:
[Serializable, ClassInterface(ClassInterfaceType.AutoDual)]
class helperDomain<T>: MarshalByRefObject where T: class
{
#region private
private AppDomain _app_domain;
private AppDomainSetup _app_domain_info;
private string _assembly_class_name;
private string _assembly_file;
private string _assembly_file_name;
private T _inner_class;
private bool _load_ok;
private string _loading_errors;
private string _path;
#endregion
#region .ctor
public helperDomain(string AssemblyFile,
string configFile = null, string domainName)
{
this._load_ok = false;
try
{
this._assembly_file = AssemblyFile; //full path to assembly
this._assembly_file_name = System.IO.Path.GetFileName(this._assembly_file); //assmbly file name
this._path = System.IO.Path.GetDirectoryName(this._assembly_file); //get root directory from assembly path
this._assembly_class_name = typeof(T).ToString(); //the class name to instantiate in the domain from the assembly
//start to configure domain
this._app_domain_info = new AppDomainSetup();
this._app_domain_info.ApplicationBase = this._path;
this._app_domain_info.PrivateBinPath = this._path;
this._app_domain_info.PrivateBinPathProbe = this._path;
if (!string.IsNullOrEmpty(configFile))
{
this._app_domain_info.ConfigurationFile = configFile;
}
//lets create the domain
this._app_domain = AppDomain.CreateDomain(domainName, null, this._app_domain_info);
//instantiate the class
this._inner_class = (T) this._app_domain.CreateInstanceFromAndUnwrap(this._assembly_file, this._assembly_class_name);
this._load_ok = true;
}
catch (Exception exception)
{
//There was a problema setting up the new appDomain
this._load_ok = false;
this._loading_errors = exception.ToString();
}
}
#endregion
#region public properties
public string AssemblyFile
{
get
{
return _assembly_file;
}
}
public string AssemblyFileName
{
get
{
return _assembly_file_name;
}
}
public AppDomain AtomicAppDomain
{
get
{
return _app_domain;
}
}
public T InstancedObject
{
get
{
return _inner_class;
}
}
public string LoadingErrors
{
get
{
return _loading_errors;
}
}
public bool LoadOK
{
get
{
return _load_ok;
}
}
public string Path
{
get
{
return _path;
}
}
#endregion
}
and then load plugins (each in a diferent folder).
foreach(string pluginassemblypath in pluginspaths)
{
//Each pluginassemblypath (as it says..) is the full path to the assembly
helperDomain<IPluginClass> isoDomain =
helperDomain<IPluginClass>(pluginassemblypath,
pluginassemblypath + ".config",
System.IO.Path.GetFileName(pluginassemblypath) + ".domain");
if (isoDomain.LoadOK)
{
//We can access instance of the class (.InstancedObject)
Console.WriteLine("Plugin loaded..." + isoDomain.InstancedObject.GetType().Name);
}
else
{
//Something happened...
Console.WriteLine("There was en error loading plugin " +
pluginassemblypath + " - " + helperDomain.LoadingErrors);
}
}
Hope it will helps you...

This question seems relevant to what you want to do.
How to Load an Assembly to AppDomain with all references recursively?
After you've loaded the assembly, you can use Assembly.GetTypes() and iterate to find the types that implement your interface.

Related

could not load assemly error when try to load plugins in c#

I want to create a Plugin architecture so I created the following interface
public interface IPlug
{
string Id { get; }
string Name { get; }
byte IsOn { get; }
bool Execute();
}
Now I reference the above interface to another class library project.
namespace PlugANameSpace
{
public class PlugA : IPlug
{
private byte _isOn;
public string Id
{
get {return "6666"; }
}
public byte IsOn
{
get { return _isOn; }
}
public string Name
{
get { return "PlugA"; }
}
public PlugA()
{
LoadFromRegistry();
}
public bool Execute()
{
// do some thing that returns true for success or false for error
}
private void LoadFromRegistry()
{
//register in registry
}
}
}
The above class library is copied into the main assembly file and stored in a folder "Plugins". Then I tried to load the plugin with the following code.
IPlug plug= Activator.CreateInstanceFrom(file, typeof(IPlug).FullName) as IPlug;
file is dll file got from Directory.GetFiles method.
When I tried to create instance, it throws error " Could not load type 'IPlug ' from assembly 'PlugA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. "
what I am doing wrong.?
You need to specify the name of the type in the PlugA assembly.
IPlug plug = Activator.CreateInstanceFrom(file, "PlugANameSpace.PlugA") as IPlug;
Edit: If you want to load a plugin without knowing the name of the type:
var assemblyName = AssemblyName.GetAssemblyName(file);
var assembly = Assembly.Load(assemblyName);
var pluginType = assembly.GetTypes().FirstOrDefault(t => typeof(IPlug).IsAssignableFrom(t));
IPlug plug = Activator.CreateInstance(pluginType) as IPlug;

How to load assemblies in different folders C#

I need load a DLL and dependencies. In my database I already save all dependencies (path to the references files).
I.E:
DLL to load:
id: 1
name:"DummyModule.dll"
Dependencies:
DLL id: 1
path: "C:\DLL\ABC.dll"
AssemblyLoader class:
public class AssemblyLoader : MarshalByRefObject
{
public void Load(string path)
{
ValidatePath(path);
Assembly.Load(path);
}
public void LoadFrom(string path)
{
ValidatePath(path);
Assembly.LoadFrom(path);
}
public void LoadBytes(string path)
{
ValidatePath(path);
var b = File.ReadAllBytes(path);
Assembly.Load(b);
}
public Assembly GetAssembly(string assemblyPath)
{
try
{
return Assembly.Load(assemblyPath);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public Assembly GetAssemblyBytes(string assemblyPath)
{
try
{
var b = File.ReadAllBytes(assemblyPath);
return Assembly.Load(b);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
private void ValidatePath(string path)
{
if (path == null)
throw new ArgumentNullException("path");
if (!File.Exists(path))
throw new ArgumentException(String.Format("path \"{0}\" does not exist", path));
}
}
The main class:
static void Main(string[] args)
{
string file1 = #"1\DummyModule.dll";
string file2 = #"2\PSLData.dll";
string file3 = #"3\Security.dll";
try
{
AppDomain myDomain = AppDomain.CreateDomain("MyDomain");
var assemblyLoader = (AssemblyLoader)myDomain.CreateInstanceAndUnwrap(typeof(AssemblyLoader).Assembly.FullName, typeof(AssemblyLoader).FullName);
assemblyLoader.LoadBytes(file2);
assemblyLoader.LoadBytes(file3);
var dummy = assemblyLoader.GetAssemblyBytes(file1);
foreach (var t in dummy.GetTypes())
{
var methodInfo = t.GetMethod("D");
if (methodInfo != null)
{
var obj = Activator.CreateInstance(t);
Console.Write(methodInfo.Invoke(obj, new object[] { }).ToString());
}
}
AppDomain.Unload(myDomain);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
Console.ReadKey();
}
In the code above the "DummyModule.dll" is the main dll, "PSLData.dll" and "Security.dll" are the dependencies.
When I call the method "D" of my "DummyModule.dll" the error appears:
Could not load file or assembly 'DummyModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
All DLL files still in different folders. How I can load all needed files and call a function?
Thanks.
Try using this.. it worked for me..
serviceAgentAssembly =System.Reflection.Assembly.LoadFrom(string.Format(CultureInfo.InvariantCulture, #"{0}\{1}", assemblyPath, assemblyName));
foreach (Type objType in serviceAgentAssembly.GetTypes())
{
//further loops to get the method
//your code to ivoke the function
}
You're using relative paths to the assemblies, so the question is "relative to what?" The new AppDomain you've created and are loading assemblies into is lost in the woods; it doesn't inherit the same probe paths of the AppDomain in which you created it. Take a look at the class System.AppDomainSetup and its properties ApplicationBase and PrivateBinPath along with the form of CreateDomain() that takes an instance of AppDomainSetup as an argument. The simplest solution would be to use the AppDomainSetup instance returned by AppDomain.CurrentDomain.SetupInformation were the current domain is, of course, the app in which the new domain is created.

How can I deal with modules with different versions of the same dependencies in MEF?

At the moment, I have a module folder configured, and all my module assemblies and their dependencies live there. I worry that in six months time, someone builds a new module, and its dependencies overwrite the older versions of the dependencies.
Should I maybe develop some sort of module registry, where a developer registers a new module, and assigns it a sub-folder name in the modules folder? This kind of dampens the convenience of using a DirectoryCatalog though, if I have to tell the host about the modules.
I've had a similar problem in the past. Below I present my solution, which I think is similar to what you are trying to accomplish.
Using MEF like this is really fascinating, but here are my words of caution:
It gets complicated quick
You have to make a couple compromises like inheriting MarshalByRefObject and plugins not building with solution
And, as I decided, simpler is better! Other non-MEF designs may be a better choice.
Ok, disclaimers out of the way...
.NET allows you to load multiple versions of the same assembly into memory, but not to unload them. This is why my approach will require an AppDomain to allow you to unload modules when a new version becomes available.
The solution below allows you to copy plugin dlls into a 'plugins' folder in the bin directory at runtime. As new plugins are added and old ones are overwritten, the old will be unloaded and the new will be loaded without having to re-start your application. If you have multiple dlls with different versions in your directory at the same time, you may want to modify the PluginHost to read the assembly version through the file's properties and act accordingly.
There are three projects:
ConsoleApplication.dll (References Integration.dll only)
Integration.dll
TestPlugin.dll (References Integration.dll, must be copied to ConsoleApplication bin/Debug/plugins)
ConsoleApplication.dll
class Program
{
static void Main(string[] args)
{
var pluginHost = new PluginHost();
//Console.WriteLine("\r\nProgram:\r\n" + string.Join("\r\n", AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetName().Name)));
pluginHost.CallEach<ITestPlugin>(testPlugin => testPlugin.DoSomething());
//Console.ReadLine();
}
}
Integration.dll
PluginHost allows you to communicate with plugins. There should only ever be one instance of PluginHost. This also acts as a polling DirectoryCatalog.
public class PluginHost
{
public const string PluginRelativePath = #"plugins";
private static readonly object SyncRoot = new object();
private readonly string _pluginDirectory;
private const string PluginDomainName = "Plugins";
private readonly Dictionary<string, DateTime> _pluginModifiedDateDictionary = new Dictionary<string, DateTime>();
private PluginDomain _domain;
public PluginHost()
{
_pluginDirectory = AppDomain.CurrentDomain.BaseDirectory + PluginRelativePath;
CreatePluginDomain(PluginDomainName, _pluginDirectory);
Task.Factory.StartNew(() => CheckForPluginUpdatesForever(PluginDomainName, _pluginDirectory));
}
private void CreatePluginDomain(string pluginDomainName, string pluginDirectory)
{
_domain = new PluginDomain(pluginDomainName, pluginDirectory);
var files = GetPluginFiles(pluginDirectory);
_pluginModifiedDateDictionary.Clear();
foreach (var file in files)
{
_pluginModifiedDateDictionary[file] = File.GetLastWriteTime(file);
}
}
public void CallEach<T>(Action<T> call) where T : IPlugin
{
lock (SyncRoot)
{
var plugins = _domain.Resolve<IEnumerable<T>>();
if (plugins == null)
return;
foreach (var plugin in plugins)
{
call(plugin);
}
}
}
private void CheckForPluginUpdatesForever(string pluginDomainName, string pluginDirectory)
{
TryCheckForPluginUpdates(pluginDomainName, pluginDirectory);
Task.Delay(5000).ContinueWith(task => CheckForPluginUpdatesForever(pluginDomainName, pluginDirectory));
}
private void TryCheckForPluginUpdates(string pluginDomainName, string pluginDirectory)
{
try
{
CheckForPluginUpdates(pluginDomainName, pluginDirectory);
}
catch (Exception ex)
{
throw new Exception("Failed to check for plugin updates.", ex);
}
}
private void CheckForPluginUpdates(string pluginDomainName, string pluginDirectory)
{
var arePluginsUpdated = ArePluginsUpdated(pluginDirectory);
if (arePluginsUpdated)
RecreatePluginDomain(pluginDomainName, pluginDirectory);
}
private bool ArePluginsUpdated(string pluginDirectory)
{
var files = GetPluginFiles(pluginDirectory);
if (IsFileCountChanged(files))
return true;
return AreModifiedDatesChanged(files);
}
private static List<string> GetPluginFiles(string pluginDirectory)
{
if (!Directory.Exists(pluginDirectory))
return new List<string>();
return Directory.GetFiles(pluginDirectory, "*.dll").ToList();
}
private bool IsFileCountChanged(List<string> files)
{
return files.Count > _pluginModifiedDateDictionary.Count || files.Count < _pluginModifiedDateDictionary.Count;
}
private bool AreModifiedDatesChanged(List<string> files)
{
return files.Any(IsModifiedDateChanged);
}
private bool IsModifiedDateChanged(string file)
{
DateTime oldModifiedDate;
if (!_pluginModifiedDateDictionary.TryGetValue(file, out oldModifiedDate))
return true;
var newModifiedDate = File.GetLastWriteTime(file);
return oldModifiedDate != newModifiedDate;
}
private void RecreatePluginDomain(string pluginDomainName, string pluginDirectory)
{
lock (SyncRoot)
{
DestroyPluginDomain();
CreatePluginDomain(pluginDomainName, pluginDirectory);
}
}
private void DestroyPluginDomain()
{
if (_domain != null)
_domain.Dispose();
}
}
Autofac is a required dependency of this code. The PluginDomainDependencyResolver is instantiated in the plugin AppDomain.
[Serializable]
internal class PluginDomainDependencyResolver : MarshalByRefObject
{
private readonly IContainer _container;
private readonly List<string> _typesThatFailedToResolve = new List<string>();
public PluginDomainDependencyResolver()
{
_container = BuildContainer();
}
public T Resolve<T>() where T : class
{
var typeName = typeof(T).FullName;
var resolveWillFail = _typesThatFailedToResolve.Contains(typeName);
if (resolveWillFail)
return null;
var instance = ResolveIfExists<T>();
if (instance != null)
return instance;
_typesThatFailedToResolve.Add(typeName);
return null;
}
private T ResolveIfExists<T>() where T : class
{
T instance;
_container.TryResolve(out instance);
return instance;
}
private static IContainer BuildContainer()
{
var builder = new ContainerBuilder();
var assemblies = LoadAssemblies();
builder.RegisterAssemblyModules(assemblies); // Should we allow plugins to load dependencies in the Autofac container?
builder.RegisterAssemblyTypes(assemblies)
.Where(t => typeof(ITestPlugin).IsAssignableFrom(t))
.As<ITestPlugin>()
.SingleInstance();
return builder.Build();
}
private static Assembly[] LoadAssemblies()
{
var path = AppDomain.CurrentDomain.BaseDirectory + PluginHost.PluginRelativePath;
if (!Directory.Exists(path))
return new Assembly[]{};
var dlls = Directory.GetFiles(path, "*.dll").ToList();
dlls = GetAllDllsThatAreNotAlreadyLoaded(dlls);
var assemblies = dlls.Select(LoadAssembly).ToArray();
return assemblies;
}
private static List<string> GetAllDllsThatAreNotAlreadyLoaded(List<string> dlls)
{
var alreadyLoadedDllNames = GetAppDomainLoadedAssemblyNames();
return dlls.Where(dll => !IsAlreadyLoaded(alreadyLoadedDllNames, dll)).ToList();
}
private static List<string> GetAppDomainLoadedAssemblyNames()
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
return assemblies.Select(a => a.GetName().Name).ToList();
}
private static bool IsAlreadyLoaded(List<string> alreadyLoadedDllNames, string file)
{
var fileInfo = new FileInfo(file);
var name = fileInfo.Name.Replace(fileInfo.Extension, string.Empty);
return alreadyLoadedDllNames.Any(dll => dll == name);
}
private static Assembly LoadAssembly(string path)
{
return Assembly.Load(File.ReadAllBytes(path));
}
}
This class represents the actual Plugin AppDomain. Assemblies resolved into this domain should load any dependencies they require from the bin/plugins folder first, followed by the bin folder, since it is part of the parent AppDomain.
internal class PluginDomain : IDisposable
{
private readonly string _name;
private readonly string _pluginDllPath;
private readonly AppDomain _domain;
private readonly PluginDomainDependencyResolver _container;
public PluginDomain(string name, string pluginDllPath)
{
_name = name;
_pluginDllPath = pluginDllPath;
_domain = CreateAppDomain();
_container = CreateInstance<PluginDomainDependencyResolver>();
}
public AppDomain CreateAppDomain()
{
var domaininfo = new AppDomainSetup
{
PrivateBinPath = _pluginDllPath
};
var evidence = AppDomain.CurrentDomain.Evidence;
return AppDomain.CreateDomain(_name, evidence, domaininfo);
}
private T CreateInstance<T>()
{
var assemblyName = typeof(T).Assembly.GetName().Name + ".dll";
var typeName = typeof(T).FullName;
if (typeName == null)
throw new Exception(string.Format("Type {0} had a null name.", typeof(T).FullName));
return (T)_domain.CreateInstanceFromAndUnwrap(assemblyName, typeName);
}
public T Resolve<T>() where T : class
{
return _container.Resolve<T>();
}
public void Dispose()
{
DestroyAppDomain();
}
private void DestroyAppDomain()
{
AppDomain.Unload(_domain);
}
}
Finally your plugin interfaces.
public interface IPlugin
{
// Marker Interface
}
The main application needs to know about each plugin so an interface is required. They must inherit IPlugin and be registered in the PluginHost BuildContainer method
public interface ITestPlugin : IPlugin
{
void DoSomething();
}
TestPlugin.dll
[Serializable]
public class TestPlugin : MarshalByRefObject, ITestPlugin
{
public void DoSomething()
{
//Console.WriteLine("\r\nTestPlugin:\r\n" + string.Join("\r\n", AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetName().Name)));
}
}
Final thoughts...
One reason that this solution worked for me is that my plugin instances from the AppDomain had a very short lifetime. However, I believe that modifications could be made to support plugin objects with a longer lifetime. This would likely require some compromises like a more advanced plugin wrapper that could perhaps recreate the object when the AppDomain is reloaded (see CallEach).

Load dll into another domain exception

Hi I am loading dll into another domain, it works fine when loaded into that domain but when i want some information from that domain through proxy object it gives me exception below is the code for review is there any wrong step ???
public class AssemblyProxy
{
System.Type[] _types;
public System.Type[] GetTypes()
{
return _types;
}
public string FullName { get; set; }
public void LoadAssembly(string path)
{
try
{
Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
AppDomain TestDomain = AppDomain.CreateDomain("AssemblyDomain", evidence, AppDomain.CurrentDomain.BaseDirectory, System.IO.Path.GetFullPath(path), true);
Proxy _asmProxy = (Proxy)TestDomain.CreateInstanceFromAndUnwrap(AppDomain.CurrentDomain.BaseDirectory+"Common.dll", typeof(Proxy).FullName);
_asmProxy.LoadAssembly(path);
FullName = _asmProxy.FullName;
_types = _asmProxy.GetTypes(); //Here i got Exception [Can not load file or assembly]
AppDomain.Unload(TestDomain);
}
catch (Exception ex)
{
}
}
}
class Proxy : MarshalByRefObject
{
System.Type[] _types;
public string FullName { get; set; }
public System.Type[] GetTypes()
{
return _types;
}
public void LoadAssembly(string path)
{
System.Reflection.Assembly _assembly = System.Reflection.Assembly.Load(System.IO.File.ReadAllBytes(path));
_types = _assembly.GetTypes();
FullName = _assembly.FullName;
}
}
The exception I get is:
Can not load file or assembly
The way I solved this problem was by calling LoadFrom (not Load) and in the context of the AppDomain:
sDomain = AppDomain.CreateDomain(DOMAIN_NAME);
sDomain.DoCallBack(AppDomainCallback);
// runs in the context of the AppDomain
private void AppDomainCallback()
{
Assembly assembly = Assembly.LoadFrom(mAssemblyName);
}
I Have solved the issue by reading following Blog Post: the problem in my case is that i am returning System.Type Object from new domain which is no allowed you can return strings from proxy object but not System.Type object
Link

How to check if an assembly contains unit tests without loading it?

I'm currently using the following method to check for test assemblies:
private bool IsTestAssembly(string path)
{
var assembly = Assembly.LoadFrom(path);
foreach (var type in assembly.GetTypes())
{
var a = type.GetCustomAttributes(true).Select(x => x.ToString());
if (a.Contains("Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute"))
return true;
}
return false;
}
But I would like to check this without loading the assembly in memory because I need to be able to delete it afterwards in case the verification fails.
I was hoping I could simply unload the assembly, but I soon discovered that, according to MSDN:
There is no way to unload an individual assembly without unloading all of the application domains that contain it.
Thanks in advance!
I worked out a short solution as suggested by TheGreatCO, i.e. to load the assembly in a new AppDomain:
1) Usage:
// assemblies are unloaded on disposal
using (var analyser = new AssemblyAnalyser())
{
var path = "my.unit.tests.dll";
var b = analyser.IsTestAssembly(path);
Assert.IsTrue(b);
}
2) Implementation:
public class AssemblyAnalyser : MarshalByRefObject, IDisposable
{
public AssemblyAnalyser()
{
var evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
var appSetup = new AppDomainSetup()
{
ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
};
appDomain = AppDomain.CreateDomain(otherDomainFriendlyName, evidence, appSetup);
}
public bool IsTestAssembly(string assemblyPath)
{
if (AppDomain.CurrentDomain.FriendlyName != otherDomainFriendlyName)
{
var analyser = appDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, GetType().FullName);
return ((AssemblyAnalyser)analyser).IsTestAssembly(assemblyPath);
}
else
{
var assembly = Assembly.LoadFrom(assemblyPath);
return ContainsTestClasses(assembly);
}
}
public void Dispose()
{
if (AppDomain.CurrentDomain.FriendlyName != otherDomainFriendlyName)
{
AppDomain.Unload(appDomain);
GC.SuppressFinalize(this);
}
}
~AssemblyAnalyser()
{
Dispose();
}
private bool ContainsTestClasses(Assembly assembly)
{
foreach (var type in assembly.GetTypes())
{
var attr = type.GetCustomAttributes(true).Select(x => x.ToString());
if (attr.Contains("Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute"))
return true;
}
return false;
}
private const string otherDomainFriendlyName = "AssemblyAnalyser";
private AppDomain appDomain;
}
Inspect the assemblies using Mono.Cecil. Cecil does not need to load the assembly to inspect it.

Categories

Resources