natemcmaster / DotNetCorePlugins

.NET Core library for dynamically loading code

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] Detect Plugin is Host Assembly.

Simonl9l opened this issue · comments

We have a subsystem that uses plugins. In a use case where we are building Integration Tests (using NUnit) the plugin interfaces form the interfaces to that subsystem.

Effectively that NUint assembly has classes that also implement the plugin interfaces each as a mock of sorts. The subsystem tries to load the Unit Assembly to get to those plugin interfaces on the basis that I need to be able to get to those interfaces from the Unit test assembly to invoke the specifics of the tests.

The plan was to use a static class to manage the integration.

When one uses the PluginLoader.CreateFromAssemblyFile it of course loads another instance of the assembly. This instance appears to have a different static scope so the NUnit Test classes can't get to the same instance of the static class as the plugin do.

I'm trying to minimize impact of custom code to make the tests work, so do you have any recommendations on if its possible to short circuit and create a PluignLoader class directly by otherwise detecting that the assembly is already loaded and attach a PluginLoader to it?

If I understand this correctly, if this is possible that it will use the same instance of the assembly and the static classes data will be shareable?

Id assume to disable both EnableHotReload, and IsUnloadable

FYI. this is what I did and its seems to work:

 var fullAssemblyPath = Path.GetFullPath(pluginConfiguration.FullPath(PluginRootPath));
 var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(p => !p.IsDynamic);;
 var loadedAssembly = assemblies.FirstOrDefault(assembly1 =>assembly1.Location == fullAssemblyPath);
 var (pluginLoader, assembly) = loadedAssembly is not null
     ? (CreateLoader(fullAssemblyPath), loadedAssembly)
     : LoadAssembly(fullAssemblyPath);