Coffeehouse Post

Single Post Permalink

View Thread: Using MEF for the first time : any words of experience?
  • User profile image

    Im actually using mef for a large:ish project at work and i find it really addicting actually, its really handy to just import what ever instances i need in a perticular class and not have to worry about how they actually get there.

    I've also gone the route of having a 'Core' assembly for all the models and interfaces and lots of other assemblies whith actual implementations.

    I've also found generic mef contracts to be very useful, my app is an mvvm app and all the views implement an interface IView<TViewModel> where TViewModel is the type of the viewmodel the view is supposed to present.

    I then have a property in my main viewmodel of type Object that represent the active view(model), and when i set that to a viewmodel a custom value converter that looks for the appropriate IView<TViewModel> in mef.

    Perhaps it sounds a little complicated but its quite nice, because viewmodels are never aware of the actual view, even when they get displayed in the ui, the View <-> Viewmodel resolution is done by mef via the custom value converter, and its just 10 lines of code (even though one is kinda long):

        public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture ) {
          if( value != null && Container != null ) {
            var type = typeof( IView<> ).MakeGenericType( value.GetType( ) );
            var view = ( Control )Container.GetExports( new ContractBasedImportDefinition( AttributedModelServices.GetContractName( type ), AttributedModelServices.GetTypeIdentity( type ), null, ImportCardinality.ExactlyOne, false, false, CreationPolicy.Any ) ).First( ).Value;
            view.DataContext = value;
            return view;
            return null;


    There are some stuff that will get me from time to time, not huge issues but something to be aware of. Mef employs what they call stable composition, this means that if a part A has a dependency (via an import) on another part B, and there is not available instance of B, then mef wont include any instances of A in the composition either.

    This actually makes a lot of sense, but no error is thrown when this happens, but mef instead prints a warning to the output window. If some of your ImportMany properties are inexplicably empty, then this might be happening.

    Another thing to be aware of is that contract types are not checked at compile time, its perfectly fine to export a class as IFoo, without actually implementing IFoo on the class it self. Contract names are really just strings and you can indeed use strings as contract names.

    Mef will throw an error at runtime if it turns out it could not assign an instance of the export to a perticular import because of conflicting types.