Reputation: 14787
My application loads all library assemblies located in its executing path and executes preknown methods against contained classes.
I now need to do the same with an assembly that references my application assembly. Is this possible and are there any negative implications that I should be aware of?
Master Assembly:
public abstract class TaskBase
{
public abstract void DoWork();
}
LoadAssemblyFromFile("Assembly0001.dll");
Assembly0001.Task1.DoWork();
Child Assemblies:
public sealed class Task1: MasterAssembly.TaskBase
{
public override void DoWork { /* whatever */ }
}
Upvotes: 8
Views: 1142
Reputation: 6207
You did not post code of your LoadAssemblyFromFile("...") method, but if it uses Assembly.LoadFrom() or Assembly.LoadFile() to loads assemblies, you could get InvalidCastException, MissingMethodException or other exceptions, especially if your application and loaded assembly both references identical other assembly. LoadFrom() and LoadFile() loades assemblies in different binding context than your application is in. See this for detailed explanation.
Upvotes: 0
Reputation: 814
The only "problem" is that you can't write Assembly0001.Task1 in your Master assembly but you can find the correct task in the loaded assembly and invoke that one:
var asm = LoadAssemblyFromFile("Assembly0001.dll");
var taskType = asm.GetTypes().FirstOrDefault(t => typeof(TaskBase).IsAssignableFrom(t));
var task = (TaskBase)Activator.CreateInstance(taskType);
task.DoWork();
You'll still need to add some extra safety checks :)
Upvotes: 0
Reputation: 34297
Yes, this is possible. As long as your master assembly doesn't reference the child assemblies, you should be fine. Otherwise, you'll have a circular dependency.
The master assembly will simply load the child assemblies and know nothing about them except that they implement an interface. That way, the master assembly doesn't need to reference the child assemblies.
No gotchas as far as I'm aware. We use this technique successfully for certain scenarios.
Upvotes: 6
Reputation: 22158
In my experience there is nothing wrong with this. In fact, MEF uses this technique in the form of AssemblyCatalog
(where your implementations are IN the master assembly) and DirectoryCatalog
(where the implementations of an interface are in assemblies in a specific directory).
Both can be used together in an AggregateCatalog
with no problems.
Upvotes: 1