Skip to content

Instantly share code, notes, and snippets.

@danielmarbach
Created March 22, 2012 19:28
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 danielmarbach/2162411 to your computer and use it in GitHub Desktop.
Save danielmarbach/2162411 to your computer and use it in GitHub Desktop.
NUnit Action Container magic
public interface IConfigurator
{
T GetInstance<T>();
void Inject<T>(T instance);
}
public interface INeedToConfigure
{
IConfigurator Configurator { set; }
}
[TestFixture]
[UseContainer]
public class SampleTest : INeedToConfigure
{
public IConfigurator Configurator { set; private get; }
[Test]
public void SimpleTestOne()
{
}
[Test]
public void SimpleTestTwo()
{
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface,
AllowMultiple = true)]
public sealed class UseContainerAttribute: Attribute, ITestAction, IConfigurator
{
private IContainer container;
public void BeforeTest(TestDetails details)
{
this.container = Root.Container.GetNestedContainer();
INeedToConfigure configure = details.Fixture as INeedToConfigure;
if(configure != null) {
configure.Configurator = this;
}
}
public void AfterTest(TestDetails details)
{
this.container.Dispose();
}
public ActionTargets Targets
{
get { return ActionTargets.Suite; }
}
public void Inject<T>(T instance)
{
this.container.Configure(cfg => cfg.For<T>().Use(instance));
}
public T GetInstance<T>()
{
return this.container.GetInstance<T>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment