Web application developer

Generic plugin loader with MEF

monackfr .net

Written by: willem | Jun 9 2013 9:13 PM

Since The Monack Framework will be extendable with modules, I have been looking for an easy way to load assemblies and implement their interfaces. For this I found the Managed Extensibility Framework, also called MEF.

MEF is an open source library that is included in .net 4.0 and higher or can be downloaded here.

The documentation is quite clear, especially if you do the simple calculator example. But the example is still quite extensive if you want to load a lot of different interfaces, so I made a generic class to load interfaces:

public class Loader<T>
{
        [ImportMany]
        private List<T> _available;

        public IEnumerable<T> LoadedItems
        {
            get
            {
                return _available;
            }
        }

        public Loader(string path)
        {
            this.Load(path);
        }

        private void Load(string path)
        {
            var container = new CompositionContainer(new AssemblyCatalog(path));
            container.ComposeParts(this);
        }
}

With this class you can easily load interfaces of an assembly:

List<IAuthorization> authorizations = new List<IAuthorization>();

Loader<IAuthorization> loader = new Loader<IAuthorization>(@"D:\code\MonackFr\MonackFr.Mvc\bin\UserManagement.dll");
authorizations.AddRange(loader.LoadedItems);

Of course you still need to set the export annotation in the classes that implement IAuthorization:

[Export(typeof(IAuthorization))]
public class UserController : IAuthorization
{

}

1 Comment

  • Nice and lean class but still has a hardcoded assembly location. Would be nice to have a configuration file so you don't need to compile.
    Maybe some switches for loading debug/unit test or release implementations.

    I like your site,

    Alfred

    Alfred said
Add a Comment

About Me

I'm a web application developer specializing in asp.net. I have skills in asp.net, C#, html5, javascript, asp.net mvc, design patterns and more.

more about me

Random background module

This module for Orchard CMS lets you upload a list of images. For every page it chooses one randomly and sets it a the background image.

Go to project page on CodePlex
Download module

The Monack Framework

This open source framework makes it easy to build and develiver custom web applications. Unfortunately I can't spent much time on it so it is still work in progress. 

More about MonackFr
Project page at CodePlex

Orchard

Since I decided to create this website in Orchard and didn't know anything about
it when I started, I also post my experiences with this CMS.