Victor
Victor

Reputation: 201

Copy (Clone) autofac registration

In a test project i found performance gap when i use Autofac latest version. I have BaseTest class that is base class for all tests. In ctor i create Autofac ContainerBuilder object, register all types, etc.

Then - build container and use it for Service Locator.

The problem is - i could not make container static and initialize it only one (not once per each test), to save ton of time on scanning assemblies for registering types, etc.

My goal - create static ContainerBuilder (or Container) - where in static ctor BaseTest i will register all types and then in usual ctor will copy this instance (with all registration) to non static property and use it for ServiceLocator.

Why i need it - because, for example TestA change/add substitution or so TestB does knows anything about that substitution. So i need clean up all customization about registration after each test set.

Do you have any ideas about how to do it? I search a lot of info in autofac - as i understand no possible to copy or clone container. Also i could not make ContainerBuilder static and in usual ctor call Build() or Update , because it`s not allowed.

Thanks in advance.

Upvotes: 1

Views: 1274

Answers (1)

Travis Illig
Travis Illig

Reputation: 23909

Autofac doesn't support cloning containers or container registrations.

Instead of changing the whole container in every test, use nested lifetime scopes. In your test fixture setup, register all of the stuff that's common to all tests that doesn't change. Then in each test, create a new lifetime scope and register the differences/overrides.

private IContainer _container;

[TestFixtureSetUp]
public void TestFixtureSetUp()
{
  var builder = new ContainerBuilder();
  // Register the common stuff, then
  this._container = builder.Build();
}

[Test]
public void SomeTest()
{
  using(var scope = this._container.BeginLifetimeScope(
    b => b.RegisterType<OverrideType>().As<IOverride>())
  {
    // Resolve things from the "scope" variable rather
    // than from the root container.
  }
}

Upvotes: 4

Related Questions