Prism+MEF: delayed a service export from prism-module

Topics: Prism v4 - WPF 4
Sep 9, 2010 at 8:05 PM

Hi,
I have an app based on Prism (v4 ctp) and MEF.
The app has a service IService1. I want this service implementation was exported by some module (not just discovered by MEF)
 

    public interface IService1 {}
    public class Service1Impl: IService1 {}

Service1Impl doesn't have ExportAttribute. This' because I want to create the implementation by hand in my Prism-module:

    [ModuleExport(typeof(SomeModule))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public SomeModule: IModule
    {
        [Export]
        public IService1 Service1 {get; private set}

        public void Initialize()
        {
            Service1 = new Service1Impl();
        }
    }

In some other components I want to get IService1's implementation through MEF Import.
The problem is how to tell MEF to do export (in SomeModule) after Initialize was called by Prism?

If I create the service's implementation in the module's constructor then everything works fine, but it's inconsistent with Prism's modules initialization process.
The thing is that Prism initializes modules after MEF's composition completes.
Moreover before creation of the service's implementation I need to perform some complex initialization logic and I don't want it to be in constructor.

So, what are my options?

Sep 13, 2010 at 6:24 PM

Hello,

What you have above should work fine.  The export definition for IService1 is exposed through your module, although it will remain null until your module is initialized.  Because the other components may be constructed before your module is initialized, they will need to use [Import] with AllowDefault=true and AllowRecomposition=true.  This will allow the IService1 property to be null until the module is initialized, and be updated with the value when the module is initialized.  You can also import a Lazy<IService1> which will prevent trying to instantiate IService1 until you actually use it.

If you end up with composition errors, post a code sample and I am happy to take a look.

Geoff Cox
Southworks