Releasing Exports

Dec 1, 2009 at 7:09 PM
I have a situation where I would like to early release some objects I pulled from my container. The pseudo-code looks something like this:
private Dictionary<object, Lazy<T>> _dict = new Dictionary<object, Lazy<T>>();

public T CreateInstance<T>()
{
    var exp = _container.GetExport<T>();
    T val = exp.Value;
    _dict.Add(val, exp);
    return val;
}

public void ZapInstance(object o)
{
    var exp = _dict[o];
    _container.ReleaseExport(exp);
}
So, the caller gets their new instance by calling CreateInstance() and does what they need to do with it. When they are done, they call ZapInstance()
to clean up after themselves. By they time the client calls ZapInstance(), the type information that was present when CreateInstance() was called
may not be available, hence ZapInstance is not a generic method.
ReleaseExport() has overloads that take either a Lazy<T> or an Export parameter. GetExport<T> returns Lazy<T>. I cannot create the dictionary shown
in my code sample since Dictionary<object, Lazy<T>> is not a valid construct. If I make it Dictionary<object, object>, that works for storing the
value, but when cleanup time rolls around I have no way of retrieving the value into a variable of a type that is acceptable to RemoveExport().
Any suggestions on how I can do this?
Thanks,
Ron