Context-based Resolution

Mar 30, 2009 at 3:03 AM
I couldn't find an easy way to do this. It is definitely doable with a whole bunch of workarounds and extra calls. If it is readily available in Unity then pls let me know.

This concept may come in play in ohter areas as well but immediately the LifetimeManager can benefit from it.

The problem is how do you get objects found or created based on contexts not being one of: global, thread, or new?
For those we have the containermanaged, perthread, and transient lifetime managers. But what if i want to create an object per session or per request?
I looked at the external lifetime manager and in itself it didn't have anything helpful.

From the caller's perspective, I'm looking for or suggesting a call similar to the following:

  MyClass myObject = container.Resolve<MyClass>(request);
  MyClass myObject = container.Resolve<MyClass>(session);
  MyClass myObject = container.Resolve<MyClass>(new ResolutionContext(request /* or session */));

When the object is being builtup, the resolution context, in this case request or session, is passed along to the registered lifetime manager (probably by the appropriate strategy).
Which means when I registered my type I must have done something like:

  container.Register<MyClass>(new ResolutionContextBasedLifetimeManager());
or a variation thereof.

When calling SetValue/GetValue methods of the lifetime manager, the resolution context must be passed along with the key (type of the object to manage).
The lifetime manager then would monitor the lifetime of my object based on this new context rather than what is immediately available to it such as the thread or global context.

Mar 30, 2009 at 6:17 AM
The general mechanism you want (pass extra values to Resolve) is not available. However, the specific things you ask for (per-Request, per-Session) are trivial to implement with a custom lifetime manager. The current request and session are available as globals, so you just need to grab them and stuff you objects in.

Mar 30, 2009 at 9:17 AM
This is exactly the kind of functionality I required myself.  Chris helped with this post

What I can now do is for each request I create a child container, use that as the container from that point onwards, and then dispose it at the end.  I can effectively use this container as if my app was a single-task single-threaded app :-)

Apr 4, 2009 at 2:29 PM
should have known better. Using TLS (or CallContext in the case of HttpContext) you can get the information you want.
Even though theoratically it is possible to have changing contexts within the lifetime of a thread which may cause the TLS model not to work I haven't encountered such cases in practice. Therefore, I'll withdraw my request/suggestion for such feature.