MEF and WCF
I'd like to use MEF for instantiating the dependencies in an application that has several WCF services hosted in IIS. The different services depend on shared components and I'd like MEF to manage the instantiation and injection of these.
Where should I perform composition? Initially I thought of having a CompositionContainer in an IInstanceProvider but then I realized that that container would only serve a single endpoint and the instances it manages will not be shared with other endpoints. Likewise with having the CompositionContainer in a ServiceHost - That would not be shared across different services.
Am I correct in this analysis? Is the only solution to have the CompositionContainer as a singleton at the application level?
A second question is - When a Service is instantiated by WCF (like when a new user session is started), how can I supply its dependencies? Do I make the CompositionContainer recompose? Wouldn't that affect other already running Service instances?
Might anyone share a code sample for this concept? Many thanks!
You used the term 'injection', and based on your requirements, I would actually suggest taking look at using an IoC container (Spring, Windsor, Unity, etc.) instead as this would provide even greater flexibility. There's also some examples of this already:
I've encountered the requirement to make WCF service composeable many times, and the approach you identified where you use a custom IInstanceProvider is the way to solve it. Aswell as writing a custom instance provider, you also need a service behaviour, and a custom service host.
In terms of code-samples, I've documented my approach on my blog: http://www.timjroberts.com/2011/08/wcf-services-with-mef/
Hope this helps.
You can use this nuget package. At project site, you can find couple examples how to use the library in web application or as self hosted service.