plugin

Unity 2 Setting up the Chain of Responsability pattern and using a configuration file with Mono (monodevelop)


Unity 2 Setting up the Chain of Responsability pattern and using a configuration file with Mono (monodevelop)

The Chain of Responsibility pattern helps to accomplish two main goals when developing software. It keeps very specific
functionality into separate modules, and by using unity we can decide easily plug and unplug functionality.

If you haven’t heard about Chain of Responsibility pattern see http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern, on the other hand, if you haven’t heard about Microsoft Unity 2 Block (an IoC or dependency injection framework, please check http://unity.codeplex.com/.

Now, lets get started with a simple sample.

1. Get Microsoft Unity 2 Block
I’m going to use mono just to show that it’s possible to use Unity on Mono ;-). So, first of all download Unity Source code from codeplex site at http://unity.codeplex.com/SourceControl/list/changesets# . Once you download the source code, you can remove tests and the compile the project. it should compile properly. (BTW I’m using Mono 2.4)

2. In our sample, the application uses repositories, to get and store user data. Our sample has create a project per layer, and these projects communicate by implementing the interfaces (contracts) from the Infrastructure project. Lets see some notes about each layer.

  • “Data” project will retrieve real data from the data base.
  • “Dummy” project will produce dummy data.
  • “Cache” project will perform cache tasks, and then delegate the data retrival tasks to a given sucessor.
  • “Logging” project will perform logging tasks, and then delegate the data retrival to a give successor.
  • “Infrastructure” project will define the interface that is required for the UserRepository. So all projects knows what is the expected input and output for the UserRepository. Additionally it has been define a ISuccessor interface in order to identify layers that require a successor (for example Logging, Cache).

For the sake of the sample, the IUserRepository defines only one operation GetUserFullName. In this opertion, each implementation will add a text indicating that it has been performed a call to each given layer. By using unity 2 we will be able to indicate which levels will be loaded and executed through a configuration file.

using System;
namespace ChainOfResponsability.Infrastructure.Repository
{
	public interface IUserRepository
	{
		string GetUserFullName(int id);
	}
}

This code is sample of the contract that each different layer is going to implement if they want to be part of the chain for IUserRepository.
Additionally, ISuccessor is defined as following:

using System;
namespace ChainOfResponsability.Infrastructure
{
	public interface ISuccessor<T>
	{
		T Successor {get;}
	}
}

This generic interface allows to indicate a successor to perform the next call in the chain.

3. The “Logging” and “Cache” projects will implement IUserRepository and ISuccessor interfaces, and additionally they will require the successor as parameter of the constructor in order to delegate the task itself. Because of Unity 2 can only resolve one (anonymous) mapping for a given type (always into the same container). My colleague Marvin (aka Murven ) suggested a workaround. Basically, each layer which implements ISuccessor will receive in its constructor the IUnityContainer which will resolve the contract, but instead of using the given container, it will use the parent to resolve the type. So, it could get a different resolution for the same given type.

using System;
using ChainOfResponsability.Infrastructure.Repository;
using ChainOfResponsability.Infrastructure;
using ContainerExtensions = Microsoft.Practices.Unity.UnityContainerExtensions;
using Microsoft.Practices.Unity;
namespace ChainOfResponsability.Logging.Repository
{
	public class LoggingUserRespository : IUserRepository, ISuccessor<IUserRepository>
	{
		public LoggingUserRespository (IUnityContainer container)
		{
			this.Successor = ContainerExtensions.Resolve<IUserRepository> (container.Parent);
		}

		#region IUserRepository implementation
		public string GetUserFullName (int id)
		{
			return string.Format ("{0}->{1}", this.GetType ().Name, this.Successor.GetUserFullName (id));
		}
		#endregion

		#region ISuccessor[IUserRepository] implementation
		public IUserRepository Successor { get; set; }
		#endregion

	}
}
using System;
using ChainOfResponsability.Infrastructure;
using ChainOfResponsability.Infrastructure.Repository;
using Microsoft.Practices.Unity;
using ContainerExtensions = Microsoft.Practices.Unity.UnityContainerExtensions;
namespace ChainOfResponsability.Cache.Repository
{
	public class CacheUserRepository : IUserRepository, ISuccessor<IUserRepository>
	{
		public CacheUserRepository (IUnityContainer container)
		{
			this.Successor = ContainerExtensions.Resolve<IUserRepository> (container.Parent);
		}

		#region IUserRepository implementation
		public string GetUserFullName (int id)
		{
			return string.Format ("{0}->{1}", this.GetType ().Name, this.Successor.GetUserFullName (id));
		}
		#endregion

		#region ISuccessor[IUserRepository] implementation
		public IUserRepository Successor { get; set; }
		#endregion
	}
}

Even though both files owns a similar structure, each file can add a very specific functionality (caching or logging) in the previous example, and the invoke the proper successor.

4. The “Data” and “Dummy” projects will implement IUserRepository only and they will implement the task itself.

using System;
using ChainOfResponsability.Infrastructure;
using ChainOfResponsability.Infrastructure.Repository;
namespace ChainOfResponsability.Dummy.Repository
{
	public class DummyUserRepository : IUserRepository
	{
		public DummyUserRepository ()
		{
		}

		#region IUserRepository implementation
		public string GetUserFullName (int id)
		{
			return string.Format ("{0}[{1}]", this.GetType ().Name, id);
		}
		#endregion
	}
}
using System;
using ChainOfResponsability.Infrastructure;
using ChainOfResponsability.Infrastructure.Repository;
namespace ChainOfResponsability.Data.Repository
{
	public class DataUserRepository : IUserRepository
	{
		public DataUserRepository ()
		{
		}

		#region IUserRepository implementation
		public string GetUserFullName (int id)
		{
			return string.Format ("{0}[{1}]", this.GetType ().Name, id);
		}
		#endregion
	}
}

In the case of “Data” and “Dummy” layers, they don’t need a successor so they can perform the task itself and return the proper result.

6. There is an additional step, which is to load all the containers from the configuration file. Basically it’s done by looping through all the containers and asking for a new child on each iteration. So, we can create a sort of chain of containers where each one owns a different type resolution for the save given type. I’ve created an small utility which load the different containers and create a chain (container and parents).

        public static IUnityContainer container;
	private static void UnityBootStrap()
        {
            container = new UnityContainer();
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            #region Mappings based on the configuration file
            IUnityContainer currentContainer = container;
            foreach (var containerSection in section.Containers)
            {
                var nestedContainer = currentContainer.CreateChildContainer();
                Microsoft.Practices.Unity.Configuration.UnityContainerExtensions.LoadConfiguration(nestedContainer, section, containerSection.Name);
                currentContainer = nestedContainer;
            }
            container = currentContainer;
            #endregion
        }

This code loads the configuration file of Unity, and creates a containers which has a parent, and its parent has a different parent and so on. In this way we can create a chain with different mappings to the same IUserRepository contract. Additionally the following configuration file has been defined:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  	<!-- Defines some aliast to easily manipulate the mappings -->
    <alias alias="IUserRepository" type="ChainOfResponsability.Infrastructure.Repository.IUserRepository, ChainOfResponsability.Infrastructure" />
    <alias alias="DataUserRepository" type="ChainOfResponsability.Data.Repository.DataUserRepository, ChainOfResponsability.Data" />
    <alias alias="DummyUserRepository" type="ChainOfResponsability.Dummy.Repository.DummyUserRepository, ChainOfResponsability.Dummy" />
    <alias alias="CacheUserRepository" type="ChainOfResponsability.Cache.Repository.CacheUserRepository, ChainOfResponsability.Cache" />
    <alias alias="LoggingUserRespository" type="ChainOfResponsability.Logging.Repository.LoggingUserRespository, ChainOfResponsability.Logging" />

    <!-- Default Container when creating the tree-chain of resolution-->
    <container>
    </container>
    <!-- lowest level of the resolution chain -->
    <container name="DummyContainer">
      <register type="IUserRepository" mapTo="DummyUserRepository">
        <lifetime type="ContainerControlledLifetimeManager" />
      </register>
    </container>
    <container name="DataContainer">
      <register type="IUserRepository" mapTo="DataUserRepository">
        <lifetime type="ContainerControlledLifetimeManager" />
      </register>
    </container>
    <!-- Middle tiers. They can be added as many as needed, while they implement the proper interface -->
    <!-- Concrete implementations are chained because they're properly implementing ISuccessor interface -->
    <container name="CacheContainer">
      <register type="IUserRepository" mapTo="CacheUserRepository">
        <lifetime type="ContainerControlledLifetimeManager" />
      </register>
    </container>
    <!-- Chain of excution starts here! -->
    <container name="LoggingContainer">
      <register type="IUserRepository" mapTo="LoggingUserRespository">
        <lifetime type="ContainerControlledLifetimeManager" />
      </register>
    </container>
  </unity>
</configuration>

7. Because of we only have a common reference between projects (technically all projects are referencing “Infrastructure”, and some projects are referencing Unity. The final project does not need to reference all the implementations, but we have to copy the DLLs of each layer before running the application. If not, we will receive a message like:
The type name or alias …. could not be resolved. Please check your configuration file and verify this type name.” Assuming that you’ve written correctly all the types and DLLs names, then this error appears because the application couldn’t find the DLLs required to load the specified type. So, remember to copy the DLLs when running the application.

		public static void Main (string[] args)
		{
			UnityBootStrap();
			//var userRepository = Microsoft.Practices.Unity.UnityContainerExtensions.Resolve<IUserRepository>(container);
			var userRepository =  ContainerExtensions.Resolve<IUserRepository>(container);
			Console.WriteLine ("Call Stack of Layers when invoking GetUserFullName(0):\n {0} ", userRepository.GetUserFullName(0));
		}

At last but not least you can modify the configuration file to dynamically chance the layers that will be executed without changing your code. For example our first call will produce”

Calling our Sample with the Data Layer

And we can replace the “Data” layer with the “Dummy” layer just by commenting the “Data” layer definition into the configuration file.

Calling with Dummy Layer

Certainly this could open the door to more complex tasks and scenarios. The full source code of this sample has been hosted in GitHub at
https://github.com/hmadrigal/playground-dotnet/tree/master/MsUnity.ChainOfResponsability

Best regards,
Herber

Advertisements

Implementing a Plug-in Loader in C# (Using Unity)


Hi,

In my old post I explained a way for implementing plug-in with reflection and IO file operations, and Indeed this is one way for doing it. Currently there are frameworks that can simplify this kind of tasks, and these frameworks are more flexible. Here there are two of frameworks:

Microsoft Extensibility Framework (@  http://mef.codeplex.com/Wikipage)

From codeplex site:

“MEF presents a simple solution for the runtime extensibility problem. Until now, any application that wanted to support a plugin model needed to create its own infrastructure from scratch. Those plugins would often be application-specific and could not be reused across multiple implementations.

  • MEF provides a standard way for the host application to expose itself and consume external extensions. Extensions, by their nature, can be reused amongst different applications. However, an extension could still be implemented in a way that is application-specific. Extensions themselves can depend on one another and MEF will make sure they are wired together in the correct order (another thing you won’t have to worry about).
  • MEF offers a set of discovery approaches for your application to locate and load available extensions.
  • MEF allows tagging extensions with additonal metadata which facilitates rich querying and filtering”

Unity (@ http://unity.codeplex.com/)

From codeplex:

“The Unity Application Block (Unity) is a lightweight extensible dependency injection container with support for constructor, property, and method call injection.

Unity addresses the issues faced by developers engaged in component-based software engineering. Modern business applications consist of custom business objects and components that perform specific or generic tasks within the application, in addition to components that individually address cross cutting concerns such as logging, authentication, authorization, caching, and exception handling.

The key to successfully building such applications is to achieve a decoupled or very loosely coupled design. Loosely coupled applications are more flexible and easier to maintain. They are also easier to test during development. You can mock up shims (lightweight mock implementations) of objects that have strong concrete dependencies; such as database connections, network connections, ERP connections, and rich user interface components. ”

So, are they the same framework?

Although both frameworks struggle to allow a better application extensibility, their attack the problem from different fronts. And of course, each framework has their own set of concepts.

Let prepare a quick plug-in with unity

Before continuing, I’d like to clarify that this is only one approach for using unit, I can bet that there might be more interesting implementations, however mine is really good for getting started ;-). BTW, I’m doing this sample based on this article @ http://www.pnpguidance.net/post/UnityConfigurationSeparateConfigurationFile.aspx I’m going to try to sum up all the step I’ve followed to create this (Unity) plug in. At the end of the post (or sample) the source code will be published for download.

Project Structure

The following are the projects that have been created, and the (relevant) files that each project contains.

Sample.UnityPlugin This is the default project (in this case a console application). This project uses the plug in implementation, although it does not need to know how is the concrete implementation, this project only references to the Sample.UnityPlugin.Contracts.
Sample.UnityPlugin.Contracts This project contains common content between the plug in contract and the plug in implementation. This common content is an interface (aka Contract) which defines what the plugin must provide. This project is referenced by the two parts, the first part if the part of the application that will implement the functionality of the plug in. The second part is the part of the application that will be using the implementation of the plug in.
Sample.UnityPlugin.Cocoa This project represents the plug in implementation. It references to the Sample.UnintyPlugin.Cocoa in order to know the plugin’s contract.

Now,  lets prepare some references:
Sample.UnityPlugin needs to reference the Microsoft.Practices.UnityMicrosoft.Practices.Unity.Configuration, Sample.Unity.Contracts.
Sample.UnityPlugin.Cocoa only needs to reference to Sample.UnityPlugin.Contracts.

Defining the Plug in Contract

To implement our plug in lets start by defining the Contract (interface) in our Sample.UnityPlugin.Contracts project. The following is the contract file:

namespace Sample.UnityPlugin.Contracts
{
    public interface IProvider
    {
        object Connection { get; }
        string Name { get; }
    }
}

The IProvider only defines a “Connection” and a Name. Really simple, isn’t ?

Implementing the plug in

The concrete implementation of the plug in will be in the Sample.UnityPlugin.Cocoa (sorry, I was thinking in a Cocoa provided when I wrote this). So, our concrete implementation will be:

using Sample.UnityPlugin.Contracts;

namespace Sample.UnityPlugin.Cocoa
{
    public class Provider : IProvider
    {
        public Provider(string providerName)
        {
            this.Name = providerName;
        }

        public object Connection { get; set; }

        public string Name { get; set; }
    }
}

As you might notices the implementation references the contract (aka interface), and implements the behavior for this contract.

Consuming the plugin

Now lets add the unity.config file to the Sample.UnityPlugin application. The Unity configuration can be loaded from a configuration file, o being set by code.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <unity>
    <typeAliases>
      <typeAlias alias="string" type="System.String, mscorlib" />
      <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
      <typeAlias alias="IProvider" type="Sample.UnityPlugin.Contracts.IProvider, Sample.UnityPlugin.Contracts" />
      <typeAlias alias="Provider" type="Sample.UnityPlugin.Cocoa.Provider, Sample.UnityPlugin.Cocoa" />
    </typeAliases>
    <containers>
      <container name="container">
        <types>
          <type type="IProvider" mapTo="Provider" >
            <lifetime type="singleton" />
            <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
              <constructor>
                <param name="providerName" parameterType="string">
                  <value value="The big Cocoa Provider (tm)"/>
                </param>
              </constructor>
            </typeConfig>
          </type>
        </types>
      </container>
    </containers>
  </unity>
</configuration>

In a quick review this configuration file is in charge of making the connection between contract and the concrete implementation, by doing it in a configuration file.
It can be changed any time (by providing the correct files). Please, notices that the configuration file is able to call the Provider constructor and send custom values to it.
Also the application is able to label relations between contracts and implementations, and group them into a container, which can be labeled too.
The last comment is about the location of this file, this file uses Configuration API, so it can be referenced indirectly by your app.config (or web.config), however in this sample it’s being loaded
and referenced directly in the code.

Now lets write our main code that will load the plug in:

using System.Text;
using Microsoft.Practices.Unity;
using System.Configuration;
using Microsoft.Practices.Unity.Configuration;
using Sample.UnityPlugin.Contracts;

namespace Sample.UnityPlugin
{
    class Program
    {
        private static IUnityContainer GetContainer()
        {

            var map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = "unity.config";
            var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            var section = (UnityConfigurationSection)config.GetSection("unity");
            var container = new UnityContainer();
            section.Containers["container"].Configure(container);
            return container;
        }

        static void Main(string[] args)
        {
            IUnityContainer container = GetContainer();
            var myProvider = container.Resolve<IProvider>();
            System.Console.WriteLine("Provider Name:{0}", myProvider.Name);
            System.Console.ReadKey();
        }
    }
}

Get container function will load our custom plugin, and the main function will make use of it.
At this time, this post is quite big, and certainly there is more things that unity can do. I’ll try to provide a plug in implementation using MEF, but in my next post 😉

BTW, I almost forgot … here is the source code (Visual Studio 2010 and Unity 2 beta)
https://github.com/hmadrigal/playground-dotnet/tree/master/MsDotNet.PluginWithUnity
Herberth

Implementando un Plugin en C# (Usando Bibliotecas de Reflection)


EDIT: Con el tiempo he aprendido otras tecnicas para crear plug ins, aqui hay un articulo con un par de ellas https://hmadrigal.wordpress.com/2010/03/28/writing-a-plug-in/ lamentablemente lo escribi en ingles, hay un ejemplo. 😛

Yo siempre me pregunte como trabajan los plugins. Entonces, yo lei articulos acerca de eso, y encontre algunas interesantes ideas. Yo he encontrado una manera para implementar plugins, que no significa que sea la ultima, pero usted puede investigar mas si esta idea no es suficiente.

When debo utilizar plugins?
Solo puedo pensar en escenarios como:

Cuando las reglas de negocios cambian muy amenudo y no quiero recompilar la aplicacion entera para actualizarla.
Para poder dar oportunidad a un tercero de implementar funcionalidad en mi aplicacion.

Entonces, que necesito para un plugin?

1. Definir un Contrato: Esta parte de la aplicacion esta a cargo de exponer toda las tareas que el pluing tiene que implementar, y tambien expone los recursos de la aplicacion que el plug in es capaz de acceder.
2. Implementacion del contrato: Esta es la implementacion de las tareas.
3. El cargador de plugins: Esta es la parte de la aplicacion encargada de cargar los archivos relacionados a la aplicacion. El resultado final es tener una manera de accessar todos los plugins cargados, junto con sus miembros.

Suena facil verdad?, de hecho, es facil!, el unico detalle es como implementar cada paso en su lenguaje de preferencia.

Yo he implementado un simple ejemplo utilizando C# 3.0, LINQ y genericos. Yo me base en un ejemplo de un articulos que encontre en internet, sin embargo agrege el soporte para genericos y LINQ para sacar ventaja del .NET framework 3.5.

Paso 1: Contrato del Plugin
En C# la mas comun manera para defininr un contrato es por medio del uso de interfaces. Entonces, nosotros solamente necesitamos creat un proyecto que almacene toas las interfaces que el plugin necesita sean implementadas, y los recursos que son compartidos entre el plug in y la aplicacion.

Paso 2: Implementacion del Plugin
Ahora tenemos que creat una clase que implemente (lo cual quiere decir escribir funcionalidad) para el contrato del paso anterior.

Step 3: Plugin loaders
Esta es la parte dificil de esto, nuestra applicacion va ha cargar archivos binarios. Estos archivos van a ser incorporados a nuestra applicacion en ejecucion. Despues de esto, nosotros podremos llamar (si se requiere) una tarea en particular de nuestro plugin. Para lograr esto en C#, nosotros utilizamos el concepto de ‘late binding’, que esta dentro del .NET framwork. Esto permite a nuestra applicacion cargar los archivos binarios en tiempo de ejecucion. Tambien al utilizar reflexion nosotros podemos generar instances de las clases de los archivos binarios.

Here is a screenshot of my sample in C#:

Adjunto un codigo de ejemplo de como implementar un cargador de plugins.
https://github.com/hmadrigal/playground-dotnet/tree/master/MsDotNet.PluginWithReflection
http://hmadrigal.googlepages.com/Transtool.zip

Tambien puede chequear estos buenos articulos:

Creating a Flexible Dynamic Plugin Architecture under .NET
http://www.codeproject.com/KB/dotnet/PluginManagerClassBrk.aspx?fid=26061&df=90&mpp=25&noise=3&sort=Position&view=Quick

ASP.NET Technical Articles – Creating a Plug-In Framework
http://msdn.microsoft.com/en-us/library/ms972962.aspx

Dynamic Loading Made Simple
http://www.codeproject.com/KB/library/dynamicloading.aspx

Enabling Your Application to Become a Plugin Host
http://www.codeproject.com/KB/cs/Plugin_Basics.aspx

Let Users Add Functionality to Your .NET Applications with Macros and Plug-Ins
http://msdn.microsoft.com/en-us/magazine/cc164072.aspx

Plugin Architecture using C#
http://www.codeproject.com/KB/cs/c__plugin_architecture.aspx

Saludos,
Herberth

Implementing a Plug-in Loader in C# (Using Reflection)


I always asked myself how the Plugins work. So I read some articles about it, and found some really interesting ideas. I’ve found the following way for implementing plugins, it does not mean that it’s the only one, but you can research more if this approach does not work for you.

When do I need to implement a plugin?
I can think in some scenarios such as:

  • When the business rules change often and you don’t want to recompile the whole application for an udpate. (You can solve this by developing with layers, and others techniques).
  • In order to give the chance to thrid party for implementing functionally in your application.

So, What do I need for a plugin?
Easy, you need 3 key parts:

  1. Contract definition: This part of you application is in charge of expose all the tasks that the plugin has to implement, and also exposes the application’s resources that the plug in allowed to access.
  2. Contract implementation: The final implementation of tasks.
  3. Plugin loader: This part of you application is going to load all the files related to the application. The final result is to have a way to access all the loaded plugins and its members.

Sounds easy right? In fact, it’s easy, the only thing is how you could implement each step in you favorite language.

I have implemented a simple loader by using C# 3.0, LINQ and Generics. I based my example on a article that I found in Internet, however I added the Generics and LINQ in order to take advantage of .NET 3.5.

Step 1: Plugin contract.
In C# the most common way for defining a contract is by using a Interface. So, we only need to create a project that is going to store all the interfaces that plug in has to implement, and the resources that are shared among the plug in and the application.

Step 2: Plugin Implementation
Now, we have to create a class that implements (which means write the functionality) for the contracts of the previous step.

Step 3: Plugin loaders
Here is the tricky part of this, our application is going to load binary files. Those files are going to be incorpored to our running application. After that, we should be able to call (if required) a particular task from a plugin. In order to do this in C#, we use ‘late binding’ concept, that .NET includes. It allows our application for loading assemblies in runtime. Also by using reflextion we can generate instances of our loaded assemblies.

Here is a screenshot of my sample in C#:


So, I’m attaching the related code as an example of how you could implement a plug in loader.
https://github.com/hmadrigal/playground-dotnet/tree/master/MsDotNet.PluginWithReflection
http://hmadrigal.googlepages.com/Transtool.zip

Also you can check some really nice articles:

Creating a Flexible Dynamic Plugin Architecture under .NET
http://www.codeproject.com/KB/dotnet/PluginManagerClassBrk.aspx?fid=26061&df=90&mpp=25&noise=3&sort=Position&view=Quick

ASP.NET Technical Articles – Creating a Plug-In Framework
http://msdn.microsoft.com/en-us/library/ms972962.aspx

Dynamic Loading Made Simple
http://www.codeproject.com/KB/library/dynamicloading.aspx

Enabling Your Application to Become a Plugin Host
http://www.codeproject.com/KB/cs/Plugin_Basics.aspx

Let Users Add Functionality to Your .NET Applications with Macros and Plug-Ins
http://msdn.microsoft.com/en-us/magazine/cc164072.aspx

Plugin Architecture using C#
http://www.codeproject.com/KB/cs/c__plugin_architecture.aspx

Regards,
Herberth