Quantcast
Channel: Nicholas Blumhardt
Viewing all articles
Browse latest Browse all 102

Convention-based part registration available in a new MEF preview!

$
0
0

There are many, many similarities between IoC-for-decoupling (as we know and love in Autofac) and IoC-for-extensibility as is implemented by MEF.

One thing that stuck out in the beginning for the MEF project members with IoC backgrounds, was the verbosity of using [Import] and [Export] attributes to describe parts, instead of the much more terse convention-driven approach used by IoC containers.

Over time, most of us grew to appreciate the role that the attributed programming model played in creating an unambiguous, decentralized configuration mechanism for plug-ins.

What the we also found was that applications using MEF for extensibility would also use it for internal composition, a-la IoC. In the much more controlled context of the host application, the lighter, more direct, convention-driven configuration model is compelling. DRY is one of the most important principles for building maintainable software, so techniques that eliminate repetition are very valuable.

It should be no surprise then, that the latest release of MEF (that I’ve only recently had any involvement in) comes with a nifty little model for defining parts by convention. The syntax should be familiar if you’re used to this kind of API:

var builder = new RegistrationBuilder();
builder.ForTypesDerivedFrom<Controller>()
    .Export()
    .SetCreationPolicy(CreationPolicy.NonShared);

When wired up to a MEF catalog, these simple conventions will read a part like:

public class HomeController :  Controller
{
    public HomeController(/* Dependencies here */) {}
    public ActionResult Index() {}
}

As:

[Export, PartCreationPolicy(CreationPolicy.NonShared)]
public class HomeController :  Controller
{
    [ImportingConstructor]
    public HomeController(/* Dependencies here */) {}
    public ActionResult Index() {}
}

RegistrationBuilder has more than a few tricks up its sleeve, and we expect to write a lot more about it on the BCL team blog in the coming weeks. For now, you can read about the new release, or even better, download the preview source and binaries from CodePlex.


Viewing all articles
Browse latest Browse all 102

Trending Articles