Search code examples
mef

Expose "services" to MEF imports


Importing parts in MEF is easy.

[ImportMany(typeof(IModule))]
public List<IModule> Modules {get; set;}

But the shell application needs to be able to provide some services to the parts.

For example the shell application has access to the datalayer, knows about authentication and authorization, etc...

Is there a simple solution. (perhaps this is really a no-brainer?) Any best practices?


Solution

  • Why not export these services?

    [Export(typeof(IMyService))]
    public class MyService : IMyService
    {
        ...
    }
    

    If the service is bound to the shell and the shell is in charge of configuring it, then you can export it as a shell property; in which case you need to remove the export attribute from the MyService class and have this:

    public class Shell : Window
    {
        [Export]
        public IMyService MyService
        {
            get
            {
                MyService service = new MyService();
    
                // initialize service
    
                return service;
            }
        }
    }
    

    Then each part can import and use them.

    [ModuleExport(typeof(MyModule))]
    public class MyModule : IModule
    {
        [Import]
        public IMyService MyService { get; set; }
    }
    

    This way you know the service is configured by the shell when it's imported.