Yep, you certainly can implement this using sharing boundaries. You will still need to trigger the creation of all the parts related to the session, e.g. by using GetExport<...>() somewhere, let me know if this bit's unclear.
First, give the user session a name, let's say "LoginSession".
We'll also create a composition root to represent the session, and share it on a per-session basis:
public class LoginSession
Then, we'll assume that somewhere you have a part controlling login that persists for the life of the application. This may be a main window or something similar, I'll just call it LoginController here as a placeholder:
public class LoginController
// _sessionFactory = sessionFactory;
Now the LoginController.Login() method:
public LoginSession Login()
Notice we return LoginSession rather than the Export<LoginSession> returned from CreateExport(): if you want to have MEF dispose the parts in a LoginSession when it completes, you'll need to keep track of the Export<LoginSession> instead, and
Dispose() it when the user logs out. In the code here the GC will pick up the parts instead, without disposing them. I'd usually dispose the Export<LoginSession> explicitly, but it is a personal preference :)
So now the only matter is how parts associated with the session get created.
The simplest and most recommended way is that they're dependencies of LoginSession, e.g.:
The d and e dependencies here, as well as any of their dependencies, will be created within the sharing boundary so long as they're either NonShared (every importer of the dependency within the session gets its own copy) or Shared("LoginSession") in which
case all importers within the boundary will get a single copy.
I'd then go and add something like a LoginSession.Show() method to kick the actual session off.
The last possible piece of the puzzle for you may be how to go and use GetExport<T>() to look up other parts within a particular boundary. The simplest way to do this is to have LoginSession accept a dependency of type CompositionContext:
// Other dependencies...
This will be injected with a context specific to the session, so calling GetExport() on it will create or retrieve parts within the boundary. Make sure you don't create a leak by doing this repeatedly for NonShared parts - if you need to create and release
an unbounded number of instances of a part within the session, check out http://mef.codeplex.com/wikipage?title=Avoiding%20reference%20%28memory%29%20leaks%20in%20MEF%20for%20Metro%20style%20apps&referringTitle=Documentation
Hope this helps, and good luck!