Unity to dispose of object
Asked Answered
S

3

8

Is there a way to make Unity dispose property-injected objects as part of the Teardown?

The background is that I am working on an application that uses ASP.NET MVC 2, Unity and WCF. We have written our own MVC controller factory that uses unity to instantiate the controller and WCF proxies are injected using the [Dependency] attribute on public properties of the controller. At the end of the page life cycle the ReleaseController method of the controller factory is called and we call IUnityContainer.Teardown(theMvcController). At that point the controller is disposed as expected but I also need to dispose the injected wcf-proxies. (Actually I need to call Close and/or Abort on them and not Dispose but that is a later problem.)

I could of course override the controllers' Dispose methods and clean up the proxies there, but I don't want the controllers to have to know about the lifecycles of the injected interfaces or even that they refer to WCF proxies.

If I need to write code myself for this - what would be the best extension point? I'd appreciate any pointer.

Sabra answered 18/9, 2009 at 9:41 Comment(0)
U
2

I've created a unity extension that will take care of disposing instances created by the container on TearDown.

See http://www.neovolve.com/2010/06/18/unity-extension-for-disposing-build-trees-on-teardown/

Urba answered 18/6, 2010 at 3:48 Comment(0)
S
0

A possible workaround is that you could also write a wrapper around your proxies that will on dispose (called by Unity when disposing instances) call a Close method of the proxy. Is that a viable scenarion for you ?

Selfliquidating answered 17/11, 2011 at 9:26 Comment(0)
W
0

Once you've got your UnityDependencyResolver

GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);

You can then call Dispose on the resolver. In ASP.NET you might choose to call this from your Global.asax.cs Application_End method like this:

GlobalConfiguration.Configuration.DependencyResolver.Dispose();

This will then call dispose on all the stuff that have container lifetime, such as instances added to the container with:

var myFooInstance = new Foo();
container.RegisterInstance<IFoo>(myFooInstance);
Washout answered 31/1, 2021 at 12:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.