Reputation: 61
I have a List of type ITemp. ITemp is a interface.
List<ITemp> temp = new List<ITemp>();
Now what I have to do is to read all the dlls from Specific file Location and add that into this temp list so what I am doing is this :
List<Assembly> allAssemblies = new List<Assembly>();
string path = Path.GetDirectoryName("C:\\TemplatesDLL\\");
foreach (string dll in Directory.GetFiles(path, "*.dll"))
{
allAssemblies.Add(Assembly.LoadFile(dll));
}
foreach (Assembly assembly in allAssemblies)
{
var DLL = Assembly.LoadFile(assembly.Location.ToString());
foreach (var t in DLL.GetTypes())
{
Activator.CreateInstance(t);
var constructors = t.GetConstructors();
temp.Add(t.GetConstructors()); // here I have to add all the dll that implements ITemp interfaces
}
}
adding the interface something like this if its in the same project
temp.Add(new TestTemp());
here TestTemp is a C# file in the same project. Now I move this TestTemp in to a DLL file. And Read it from the same application and add into the list.
Thanks in Advance.
Upvotes: 1
Views: 1164
Reputation: 61
I got it.
List<Assembly> allAssemblies = new List<Assembly>();
string path = Path.GetDirectoryName("C:\\TemplatesDLL\\");
List<ITemp> temp = new List<ITemp>();
foreach (string dll in Directory.GetFiles(path, "*.dll"))
{
allAssemblies.Add(Assembly.LoadFile(dll));
}
foreach (Assembly assembly in allAssemblies)
{
var DLL = Assembly.LoadFile(assembly.Location.ToString());
Type[] types = DLL.GetTypes();
if (typeof(ITemp).IsAssignableFrom(types[0]))
{
temp.Add(Activator.CreateInstance(types[0]) as ITemp); //adding all the instance into the list that is what I was looking for.
}
}
Upvotes: 1
Reputation: 38367
I actually needed to do this recently. This example only gets the first type, but you could easily modify it to return a list and iterate the list.
var dll = Assembly.LoadFile(@"C:\SimplePlugin.dll");
Type pluginType = dll.GetExportedTypes()
.Where(t => typeof(SimplePluginContracts.ISomePlugin).IsAssignableFrom(t)
&& !t.IsInterface).First();
SimplePluginContracts.ISomePlugin plugin =
(SimplePluginContracts.ISomePlugin)Activator.CreateInstance(pluginType);
This question covers variations on this, and the top answer has a good discussion of nuances of this technique that my simple example doesn't handle:
Getting all types that implement an interface
You might consider also filtering out non-public classes, in case your DLL has some classes not intended to be loaded which also implement the interface.
Upvotes: 0