tags:

views:

108

answers:

2

I want to do something like this:

  1. Create a number of assemblies that implement IMyInterface.
  2. In the web.config or app.config of my application, define which one of them to load (they may have different names)
  3. When the application starts, load the assembly as marked in web.config and use its implementation of IMyInterface

what is the best way of doing this? I am using Framework 3.5 at this time.

(p.s. I know I can just define a variable that contains the assembly name (e.g. key="My assembly", value="myassembly.dll" then dynamically load the assembly, just wanting to know if there is a more correct way of doing this)

+3  A: 

Assemblies do not implement interfaces; types do.

For ASP.NET apps, I suggest putting every assembly in the /bin directory and use a web.config configuration option and Activator.CreateInstance to create the actual type:

var typeName = "MyNamespace.MyClass, MyAssembly"; // load from config file
IMyInterface instance = 
              (IMyInterface)Activator.CreateInstance(Type.GetType(typeName));
Mehrdad Afshari
A: 

I do this as follows (i use base class, with abstract methods instead interfaces):

1 - List the classes implemented with my base class.

Assembly assembly = null;
AssemblyName assemblyName = new AssemblyName();
assemblyName.CodeBase = "FullPathToAssembly";

assembly = Assembly.Load(assemblyName);


Type[] arrayTipo;
arrayTipo = assembly.GetTypes();

var tipos =
from t in arrayTipo
where t.BaseType == typeof(DD.Util.BaseProcesso)
select t;

2 - Call the method of execution in an instance of the class:

Type tipo = engine.GetType("FullClassName");
BaseProcesso baseProcesso = (BaseProcesso)Activaor.CreateInstance(tipo, new object[] { "ConstructorParameter1", "ConstructorParameter1") });
// Event
baseProcesso.IndicarProgresso += new  BaseProcesso.IndicarProgressoHandler(baseProcesso_IndicarProgresso);
new Thread(new ThreadStart(baseProcesso.Executar)).Start();

Works for me!