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!

Answers


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


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.


Need Your Help

What is wrong with my PHP/MySQL code?

php mysql

I am building a navigation menu which lists all my categories and subcategories. The problem is it returns only one of these and not all. I have the categories echoed inside the while loop so I'm not

how to create a secure php login system, allowing for "keep me logged in" functionality?

php login login-script remember-me

I use a simple login system based on SESSION vars. Once the user logs in, a session var is set that tells my script the user is to be accepted in. I don't use any custom clientside cookie var.