Search code examples
asp.net-mvcmef

MefContrib: How to export composition container


I need to call CompositionContainer.GetExportedValue<> in a controller action. I use MefContrib and I need to know how and where should I add the CompositionContainer itself to the catalog so I can import it in my controller.

Update Here's the content of 'AppStart_MefContribMVC3.cs' where I believe MefContrib is configuring it's catalog. No sign on CompositionContainer here!

public static class AppStart_MefContribMVC3
{
    public static void Start()
    {
        // Register the CompositionContainerLifetimeHttpModule HttpModule.
        // This makes sure everything is cleaned up correctly after each request.
        CompositionContainerLifetimeHttpModule.Register();

        // Create MEF catalog based on the contents of ~/bin.
        //
        // Note that any class in the referenced assemblies implementing in "IController"
        // is automatically exported to MEF. There is no need for explicit [Export] attributes
        // on ASP.NET MVC controllers. When implementing multiple constructors ensure that
        // there is one constructor marked with the [ImportingConstructor] attribute.
        var catalog = new AggregateCatalog(
            new DirectoryCatalog("bin"),
            new ConventionCatalog(new MvcApplicationRegistry())); // Note: add your own (convention)catalogs here if needed.

        // Tell MVC3 to use MEF as its dependency resolver.
        var dependencyResolver = new CompositionDependencyResolver(catalog);
        DependencyResolver.SetResolver(dependencyResolver);

        // Tell MVC3 to resolve dependencies in controllers
        ControllerBuilder.Current.SetControllerFactory(
            new CompositionControllerFactory(
                new CompositionControllerActivator(dependencyResolver)));

        // Tell MVC3 to resolve dependencies in filters
        FilterProviders.Providers.Remove(FilterProviders.Providers.Single(f => f is FilterAttributeFilterProvider));
        FilterProviders.Providers.Add(new CompositionFilterAttributeFilterProvider(dependencyResolver));

        // Tell MVC3 to resolve dependencies in model validators
        ModelValidatorProviders.Providers.Remove(ModelValidatorProviders.Providers.OfType<DataAnnotationsModelValidatorProvider>().Single());
        ModelValidatorProviders.Providers.Add(
            new CompositionDataAnnotationsModelValidatorProvider(dependencyResolver));

        // Tell MVC3 to resolve model binders through MEF. Note that a model binder should be decorated
        // with [ModelBinderExport].
        ModelBinderProviders.BinderProviders.Add(
            new CompositionModelBinderProvider(dependencyResolver));
    }
}

Solution

  • It turned out that with MefContrib you don't need the CompositionContainer to resolve an exported type. Here's how it's done:

    DependencyResolver.Current.GetService<SomeTypeName>()