Auto wiring parts in ASP.NET MVC with MEF 2

In this post we’ll highlight a feature in the MEF 2 preview 4, that by convention registers parts in our mvc application. This so we can use it for DI scenarios.

Why?

What the we also found was that applications using MEF for extensibility would also use it for internal composition, a-la IoC. From Nicholas Blumhardt’s blog.

Demo

First we need to download and reference System.ComponentModel.Composition.Web.Mvc.CodePlex.dll from codeplex.

In my last post we started off with a simple model that we scaffold. We’re going to use the same model here.

Scaffold Controller Pizza –Repository


When were done our controller has a constructor that takes IPizzaRepository. (Remove the parameter less constructor)

   public PizzasController(IPizzaRepository pizzaRepository)
        {
            this.pizzaRepository = pizzaRepository;
        }

Time to let MEF wire up this dependency. The convention for auto wire is based on namespace. The repository needs to be under a namespace path of .Parts. ex Pizza.App.Parts.PizzaRepository. So to get this working all we need is to move the generated repository to a Parts folder and adjust the namespace, and done!

Run the app and the dependency for PizzaController will be wired up. This is the simple scenario with no configuration just auto magic. There is also a way for you to configure this more in detail manually, check this BCL Team post for more on convention-based part registration.

The convention also works with namespaces with Parts in it. We’ll do a quick fix in the demo code. Lets make an quick interface for our EF context.

    public interface IPizzaContext
    {
        IDbSet<Pizza> Pizzas { get; set; }

        int SaveChanges();

        DbEntityEntry Entry(object entity);
    }


Then we fix the constructor of the Pizza Repository to match.

    private IPizzaContext context;

        public PizzaRepository(IPizzaContext context)
        {
            this.context = context;
        }

The we put the context in a Data folder in the Parts folder and fix the namespace to match. Run the app and all should be wired up. Neat!

mvc_mef2_post

Of course this is a simple demo, with no consideration of life time management etc.

Conclusion

A lot is happening around .NET web with ASP.NET MVC and WCF Web Api and the integration between the two. Interesting to see what “Simplifying the use of MEF in web applications is a core goal of the new release.” (post) could add to the 4.5 web story.

Enjoy!

This Post Has 4 Comments

  1. Hi Per,

    Would you mind making your sample application available for download?

    I’m trying to put together a simple MVC test app to get my head around the new features coming to MEF but am struggling a little.

    Many thanks,
    Chris

Leave a Reply

Close Menu