Skip to content

Instantly share code, notes, and snippets.

@AGBrown
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AGBrown/2875e28a19f94a62513e to your computer and use it in GitHub Desktop.
Save AGBrown/2875e28a19f94a62513e to your computer and use it in GitHub Desktop.
Unity singleton and scope lifetimes
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