ContainerRegistration with ParameterOverride

Jan 12, 2011 at 3:34 PM

Hi,

I have some WinForms Singleton classes (with ContainerControlledLifetimeManager) in my UnityContainer which use several ParameterOverrides.

My Forms are resolved like this:

var form = Program.Container.Resolve<FormList>(new ParameterOverride("type", type));

I wrote a little extension to remove the instance from the UnityContainer when the WinForm closes, have a look:

public static void UnregisterInstance<T>(this IUnityContainer container) where T : class
{
    var reg = container.Registrations.Where(e => e.RegisteredType == typeof(T)).FirstOrDefault();
            
    if (reg != null)
    {
        // RemoveValue "automagically" calls Dispose on the object
        reg.LifetimeManager.RemoveValue();
    }
}
Is there a way I can get the ContainerRegistration for a special instance with the specified ParameterOverride?
Thanks
Sven
Jan 13, 2011 at 3:03 PM

I was able to find a solution.

I modified my extension as follows:

public static void UnregisterInstance<T>(this IUnityContainer container, string name)  
    where T : class
{
    var reg = container.Registrations.Where(e => ((e.MappedToType == typeof(T)) && (e.Name == name))).FirstOrDefault();
            
    if (reg != null)
    {
        // RemoveValue "automagically" calls Dispose on the object
        reg.LifetimeManager.RemoveValue();
    }
}
And this is my registration:
this.container.RegisterType<IMyInterface, MyView>("uniqueName", new InjectionConstructor("someValue"));

And this is how I unregister the instance:

this.container.UnregisterInstance<MyView>("uniqueName");