Unity lifetime management for IDisposable, part 3

Contents:

Limitations

In hindsight to the created solution, there is an issue that cannot be addressed in this way: When a consumer fails to call Teardown properly at the right time for constructed objects, the DisposingSharedLifetimeManager will not behave as expected. For some, this may be a big issue, because it may not be very customary to bother to call Teardown when using Unity, precisely because it usually does nothing useful anyway.

Alternative Solutions Using Unity

One alternative is to use a wrapper of sorts and register that in the container instead. The usage would look something like this:

// Registering in the container
container.RegisterInstance(typeof(SharedDisposableWrapper<IViewModel>),
               new SharedDisposableWrapper<IViewModel>(() => new ViewModel()));

// Consuming the wrapper
public class View : IDisposable
{
    private readonly SharedDisposableWrapper<IViewModel> _viewModelWrapper;

    public View(IViewModelWrapper viewModelWrapper)
    {
        _viewModelWrapper= viewModelWrapper;
        _viewModelWrapper.GetInstance();
    }

    public void Dispose()
    {
        _viewModelWrapper.ReleaseInstance();
    }
}

The implementation of this wrapper can be downloaded here if you're interested, but it not very exciting. Obviously, this approach will only work for cases where you can actually make changes to the code in question.

You can also control the lifetime of objects using child containers:

var container = new UnityContainer();
container.RegisterType(typeof(IViewModel), typeof(ViewModel),
    new HierarchicalLifetimeManager());

using (var childContainer = container.CreateChildContainer())
{
    var view1 = childContainer.Resolve<View>();
    var view2 = childContainer.Resolve<View>();

    // Done with all views, Dispose child container
}

However, messing with child containers for all kinds of things can be annoying.

Other IoC Containers

Supposedly, other IoC containers like Castle Windsor and Autofac have some options to deal with the presented scenarios. Unfortunately I do not know exactly how this looks at this point. I plan to update this article in the near future so you can make your own judgment.

Files and Links:

Comments (2) -

  • very informative article ...... and coding concept is very good... public structure is right.
  • That was a pretty interesting post, will be looking forward to your future updates.

Add comment

Loading