Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News ASP.NET MVC, Dependency Injection, and MEF 2

ASP.NET MVC, Dependency Injection, and MEF 2

This item in japanese

For most types of applications dependency injection frameworks don’t make whole lot of sense. It is usually more than sufficient to manually wire up all of the dependencies during startup and call it a day. But for ASP.NET MVC, there isn’t really one startup. Each dependency may be scoped to the server, the user session, the controller, or to an individual request. With so many competing lifecycles a DI framework quickly moves from needless distraction to an essential organizational tool.

Seeing this as an important use case, MEF 2 will include functionality specific to dealing with MVC dependencies. All this will be done using a convention-based approach; no extra configuration files will be needed.

When using MEF 2 a new folder called Parts is needed. This is where one stores classes that are going to be needed by controllers to handle things such as data access, logging, and communicating with other sites and web services. To indicate what parts are needed for a given controller, simply list them in the controller’s constructor. The same is done when a given part needs other parts.

By default parts have the lifetime of a single request and no more than one of each part will be created no matter how many controllers or other parts need it. Once the request is done, Dispose is called on any parts that need it. If a part’s lifetime should instead be that of the application, then the ApplicationShared attribute may be applied to it. Advanced registration options are available, but attribute tagging should handle most use cases.

Parts from other assemblies may be included by using the CompositionProvider.AddPartsAssembly function in Application_Start. It should be noted that all parts must include the identifier “Parts” in their namespace. The BCL team writes,

Having to use a Parts namespace for all parts may seem a little excessive, but it is a good reminder that not every class should be a part. Parts are the ‘coarse-grained’ chunks that make up an application. Assemblies that add non-trivial functionality will almost always have a large number of additional supporting classes that the parts in the assembly use, but that are not parts themselves.

Parts that represent model binders must be tagged with the ModelBinderExport attribute and the type of model it applies to.

Action filters may also participate in composition. While they cannot be created by the MEF composition provider, they can have properties filled in by MEF. To do this tag the MEF-managed property with the Import attribute.

A sample of ASP.NET MVC with MEF 2 is available on CodePlex.

Rate this Article