Proper use of [Import] attribute in MEF

13,348

Solution 1

OK what you need to do is (without prescribing for performance, this is just to see it working)

public class GeneralController : Controller
{
    [Import]
    public ITranslator Translator { get; set; }

    public JsonResult Translate(string text)
    {
        var container = new CompositionContainer(
        new DirectoryCatalog(Path.Combine(HttpRuntime.BinDirectory, "Plugins")));
        CompositionBatch compositionBatch = new CompositionBatch();
        compositionBatch.AddPart(this);
        Container.Compose(compositionBatch);

        return Json(new
        {
            source = text,
            translation = Translator.Translate(text)
        });
    }
}

I am no expert in MEF, and to be frank for what I use it for, it does not do much for me since I only use it to load DLLs and then I have an entry point to dependency inject and from then on I use DI containers and not MEF.

MEF is imperative - as far as I have seen. In your case, you need to pro-actively compose what you need to be MEFed, i.e. your controller. So your controller factory need to compose your controller instance.

Since I rarely use MEFed components in my MVC app, I have a filter for those actions requiring MEF (instead of MEFing all my controllers in my controller facrory):

public class InitialisePluginsAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        CompositionBatch compositionBatch = new CompositionBatch();
        compositionBatch.AddPart(filterContext.Controller);
        UniversalCompositionContainer.Current.Container.Compose(
            compositionBatch);
        base.OnActionExecuting(filterContext);
    }
}

Here UniversalCompositionContainer.Current.Container is a singleton container initialised with my directory catalogs.


My personal view on MEF

MEF, while not a DI framework, it does a lot of that. As such, there is a big overlap with DI and if you already use DI framework, they are bound to collide.

MEF is powerful in loading DLLs in runtime especially when you have WPF app where you might be loading/unloading plugins and expect everything else to work as it was, adding/removing features.

For a web app, this does not make a lot of sense, since you are really not supposed to drop a DLL in a working web application. Hence, its uses are very limited.

I am going to write a post on plugins in ASP.NET MVC and will update this post with a link.

Solution 2

MEF will only populate imports on the objects which it constructs itself. In the case of ASP.NET MVC, it is ASP.NET which creates the controller objects. It will not recognize the [Import] attribute, so that's why you see that the dependency is missing.

To make MEF construct the controllers, you have to do the following:

  1. Mark the controller class itself with [Export].
  2. Implement a IDependencyResolver implementation which wraps the MEF container. You can implement GetService by asking the MEF container for a matching export. You can generate a MEF contract string from the requested type with AttributedModelServices.GetContractName.
  3. Register that resolver by calling DependencyResolver.SetResolver in Application_Start.

You probably also need to mark most of your exported parts with [PartCreationPolicy(CreationPolicy.NonShared)] to prevent the same instance from being reused in several requests concurrently. Any state kept in your MEF parts would be subject to race conditions otherwise.

edit: this blog post has a good example of the whole procedure.

edit2: there may be another problem. The MEF container will hold references to any IDisposable object it creates, so that it can dispose those objects when the container itself is disposed. However, this is not appropriate for objects with a "per request" lifetime! You will effectively have a memory leak for any services which implement IDisposable.

It is probably easier to just use an alternative like AutoFac, which has a NuGet package for ASP.NET MVC integration and which has support for per-request lifetimes.

Solution 3

As @Aliostad mentioned, you do need to have the composition initialise code running during/after controller creation for it to work - simply having it in the global.asax file will not work.

However, you will also need to use [ImportMany] instead of just [Import], since in your example you could be working with any number of ITranslator implementations from the binaries that you discover. The point being that if you have many ITranslator, but are importing them into a single instance, you will likely get an exception from MEF since it won't know which implementation you actually want.

So instead you use:

[ImportMany]
public IEnumerable<ITranslator> Translator { get; set; }

Quick example:

http://dotnetbyexample.blogspot.co.uk/2010/04/very-basic-mef-sample-using-importmany.html

Share:
13,348
Saeed Neamati
Author by

Saeed Neamati

I love food, and I eat a lot.

Updated on June 22, 2022

Comments

  • Saeed Neamati
    Saeed Neamati almost 2 years

    I'm learning MEF and I wanted to create a simple example (application) to see how it works in action. Thus I thought of a simple translator. I created a solution with four projects (DLL files):

    Contracts
    Web
    BingTranslator
    GoogleTranslator

    Contracts contains the ITranslate interface. As the name applies, it would only contain contracts (interfaces), thus exporters and importers can use it.

    public interface ITranslator
    {
        string Translate(string text);
    }
    

    BingTranslator and GoogleTranslator are both exporters of this contract. They both implement this contract and provide (export) different translation services (one from Bing, another from Google).

    [Export(typeof(ITranslator))]
    public class GoogleTranslator: ITranslator
    {
        public string Translate(string text)
        {
            // Here, I would connect to Google translate and do the work.
            return "Translated by Google Translator";
        }
    }
    

    and the BingTranslator is:

    [Export(typeof(ITranslator))]
    public class BingTranslator : ITranslator
    {
        public string Translate(string text)
        {
            return "Translated by Bing";
        }
    }
    

    Now, in my Web project, I simply want to get the text from the user, translate it with one of those translators (Bing and Google), and return the result back to the user. Thus in my Web application, I'm dependent upon a translator. Therefore, I've created a controller this way:

    public class GeneralController : Controller
    {
        [Import]
        public ITranslator Translator { get; set; }
    
        public JsonResult Translate(string text)
        {
            return Json(new
            {
                source = text,
                translation = Translator.Translate(text)
            });
        }
    }
    

    and the last piece of the puzzle should be to glue these components (parts) together (to compose the overall song from smaller pieces). So, in Application_Start of the Web project, I have:

            var parts = new AggregateCatalog
                (
                    new DirectoryCatalog(Server.MapPath("/parts")), 
                    new DirectoryCatalog(Server.MapPath("/bin"))
                );
            var composer = new CompositionContainer(parts);
            composer.ComposeParts();
    

    in which /parts is the folder where I drop GoogleTranslator.dll and BingTranslator.dll files (exporters are located in these files), and in the /bin folder I simply have my Web.dll file which contains importer. However, my problem is that, MEF doesn't populate Translator property of the GeneralController with the required translator. I read almost every question related to MEF on this site, but I couldn't figure out what's wrong with my example. Can anyone please tell me what I've missed here?