-
-
Save AGBrown/2875e28a19f94a62513e to your computer and use it in GitHub Desktop.
Unity singleton and scope lifetimes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Practices.Unity; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
namespace UnityTests | |
{ | |
/// <summary> | |
/// Demonstrates a singleton registration for Unity | |
/// </summary> | |
/// <remarks> | |
/// Uses Unity 3.5.0.0 | |
/// </remarks> | |
[TestClass] | |
public class UnitySingletonTest | |
{ | |
private UnityContainer Container; | |
public interface IFoo | |
{ | |
IBar Bar { get; } | |
} | |
public interface IBar {} | |
public class Bar : IBar {} | |
public class Foo : IFoo | |
{ | |
public IBar Bar { get; private set; } | |
public Foo(IBar bar) | |
{ | |
Bar = bar; | |
} | |
} | |
[TestInitialize] | |
public void TestInitialize() | |
{ | |
Container = new UnityContainer(); | |
Container.RegisterInstance(new Bar()) | |
.RegisterType<IBar>( | |
new PerResolveLifetimeManager(), | |
new InjectionFactory(c => c.Resolve<Bar>())) | |
.RegisterType<IFoo>( | |
new PerResolveLifetimeManager(), | |
new InjectionFactory(c => c.Resolve<Foo>())); | |
} | |
[TestMethod] | |
public void FooInstancesAreDifferent() | |
{ | |
var foo1 = Container.Resolve<IFoo>(); | |
var foo2 = Container.Resolve<IFoo>(); | |
Assert.AreNotSame(foo1, foo2); | |
} | |
[TestMethod] | |
public void BarInstancesAreSame() | |
{ | |
var foo1 = Container.Resolve<IFoo>(); | |
var foo2 = Container.Resolve<IFoo>(); | |
Assert.AreSame(foo1.Bar, foo2.Bar); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment