Click here to Skip to main content
15,886,518 members
Articles / Game Development / Unity
Tip/Trick

Ensuring that your singletons in Microsoft Unity are what you expected

Rate me:
Please Sign up or sign in to vote.
4.94/5 (6 votes)
17 Oct 2014CPOL2 min read 18.3K   24   4   7
This article proposes solution for possible challenges which you can face by using singletons in Microsoft Unity in the case you are using child containers.

Introduction

When using Microsoft Unity IoC container you may face some weird issues when dealing with 'singletons' (ContainerControlledLifetimeManager) and child containers. It may or may not be what you expected.

This article discusses the issue and it also proposes a solution via a Microsoft Unity Extension.

Let's consider following classes:

C#
public interface IServiceDependency 
{ 
} 

public interface IService 
{ 
} 

public class ServiceDependency : IServiceDependency 
{ 
  private readonly string _dep1; 
  public ServiceDependency(string dep1)
  { 
    _dep1 = dep1; 
  } 
} 

public class Service : IService 
{ 
  private readonly IServiceDependency _dependency; 
  public Service(IServiceDependency dependency) 
  { 
    _dependency = dependency; 
  } 
}

Now let's setup some test case:

C#
[Test]
public void ServiceResolutionViaTwoDifferentChildContainersShouldFail()
{
    var rootContainer = new UnityContainer();

    rootContainer.RegisterType<IService, Service>(new ContainerControlledLifetimeManager());
    var childContainer = rootContainer.CreateChildContainer();
    var childContainer2 = rootContainer.CreateChildContainer();

    childContainer.RegisterInstance<IServiceDependency>(new ServiceDependency("Dep1"));
    childContainer2.RegisterInstance<IServiceDependency>(new ServiceDependency("Dep2"));

    var childContainerResult1 = childContainer.Resolve<IService>();
    var childContainerResult2 = childContainer.Resolve<IService>();
            
    var childContainer2Result1 = childContainer.Resolve<IService>();
    var childContainer2Result2 = childContainer.Resolve<IService>();

    Assert.AreEqual(childContainerResult1, childContainerResult2);
    Assert.AreEqual(childContainer2Result1, childContainer2Result2);

    Assert.AreEqual(childContainer2Result1, childContainerResult1);
}

This actually will pass all the assertions.

Let's analyze it a bit:

  • Let's step thru the test case in debugger.
  • Setup some watches:
    • ((ServiceDependency)((Service)childContainerResult1)._dependency)._dep1
    • ((ServiceDependency)((Service)childContainer2Result1)._dependency)._dep1
  • You can see that both of them point to Dep1.
    • Is that what you really wanted?
    • Consider the following case:
    • You disposed childContainer and your ServiceDependency is disposable registered as ContainerControlledLifetimeManager.
    • At this point you have invalid instance of IService (it has injected disposed ServiceDependency).
    • This is most likely a side effect of unwanted changes and you want to avoid it.
    • And this is exactly what is this extension trying to solve.
    • By enabling this extension the build operation will fail.

How to enable extension

  • Reference the UnityRegistrationValidator.dll in your project.
  • Call the registration below.
  • The extension is available as a Nuget package.
C#
var rootContainer = new UnityContainer(); 
rootContainer.AddNewExtension<EnsureRegistrationDepthOrderExtension>();

Following rules are enforced after registering extension

  • For each registration is tracked depth in containers (starting the container in which resolve starts).
  • If you register an object which
    • has dependency resolvable only inside the child container
    • and has ContainerControlledLifetimeManager()
  • the resolve will fail.
  • If you do this without the extension the resolve will succeed but the dependencies were most likely resolved in unexpected way (unless you really know what are you doing).

Conclusion

  • This extension allows you to validate the expected behavior.
  • Since it may have performance impact (it needs to track all the registrations as well as build operations) it may have negative performance impact.
  • This extension is intended to help you ensure expected behavior - but you have to always consider your circumstanes.
  • You are using this extension on your own risk :-).

References

History

  • 2014/10/27 Updated source package for new version of nuget package (thread safety bug fixes)
  • 2014/10/20 Fixed source package, updated references
  • 2014/10/18 Initial version
This article was originally posted at https://github.com/voloda/UnityRegistrationValidator

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader NCR
Czech Republic Czech Republic
I'm software developer since 1996. I started with assembler on Intel 8051 CPUs, during years I was interested in C, C++, Sybase PowerBuilder, PHP, Sybase Anywhere Database, MSSQL server and multiplatform development.

Currently I'm developing in C++ and C# (this is my favorit and I spent some time with MCPD achievement). I'm also interested in design patterns.

Comments and Discussions

 
Questionsource sample file cannot be downloadable Pin
fredatcodeproject19-Oct-14 6:31
professionalfredatcodeproject19-Oct-14 6:31 
AnswerRe: source sample file cannot be downloadable Pin
voloda220-Oct-14 10:20
voloda220-Oct-14 10:20 
GeneralRe: source sample file cannot be downloadable Pin
fredatcodeproject21-Oct-14 12:09
professionalfredatcodeproject21-Oct-14 12:09 
Questioneasy way Pin
Sacha Barber18-Oct-14 8:06
Sacha Barber18-Oct-14 8:06 
AnswerRe: easy way Pin
voloda218-Oct-14 8:27
voloda218-Oct-14 8:27 
GeneralRe: easy way Pin
Sacha Barber18-Oct-14 20:35
Sacha Barber18-Oct-14 20:35 
GeneralRe: easy way Pin
voloda220-Oct-14 2:07
voloda220-Oct-14 2:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.