views:

725

answers:

1
+1  Q: 

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!

+1  A: 

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:

http://avingtonsolutions.com/blog/post/2008/08/02/Uisng-Unity-with-a-WCF-Service.aspx

MattK
Thanks for your help. I've already gone over Steve Moseley's example. The catch there is that the container is "per WCF endpoint". With MEF I know that that prevents me from sharing exported objects across different endpoints, which for me is a showstopper. Is Unity different in this respect?
urig
So when you say 'shared components', do you mean that the shared components should maintain some state/value that would be utilized across the various services?
MattK
Yep. These are singletons. Except I'd like my IoC container to make that happen, rather than hard code them.From what I've read so far, I'd need a static factory to compose across all my different services. Castle Windsor has this under the name "WCF Integration Facility".I'd love to have something similar for MEF. But I don't know how to have it auto-wire each service instance at runtime, on demand. I'm afraid if I have a static CompositionContainer and invoke Compose() on it for every service instance, then that would have an adverse effect on service instances that are already composed.
urig
Could you possibly make use of something like IExtension<ServiceHostBase> to attach the necessary singletons upon service startup?
MattK