Unit

Case Study: Autofac & Partial Composition

Real-world integration suites often want real services wired by Autofac for part of the object graph, while leaving external boundaries mocked. ZeUnit.Autofac composes cleanly alongside ZeUnit.FakeItEasy because every IZeClassComposer returns null for types it cannot resolve.

Installation

dotnet add package ZeUnit.Autofac

Registering Services with an Autofac Module

using Autofac;

public class OrderModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<PricingService>().As<IPricingService>();
        builder.RegisterType<OrderValidator>().AsSelf();
    }
}

Composing Autofac and FakeItEasy Together

Place [AutofacModule<OrderModule>] (or [AutofacContainer(typeof(OrderModule))]) together with [Fakes] on your test suite:

using FakeItEasy;
using ZeUnit;
using ZeUnit.Autofac;
using ZeUnit.FakeItEasy;

[AutofacModule<OrderModule>]
[Fakes]
public class OrderWorkflowTests(
    IPricingService pricingService,
    OrderValidator validator,
    Fake<INotificationClient> notifications)
{
    public Fact AppliesPricingAndValidatesOrder()
    {
        var total = pricingService.CalculateTotal(3, 19.99m);
        var isValid = validator.ValidateTotal(total);

        return isValid.True();
    }
}

When ZeUnit resolves constructor arguments:

  1. AutofacContainerClassComposer uses scope.ResolveOptional(args) for IPricingService and OrderValidator, returning real container-managed instances.
  2. When Autofac returns null for Fake<INotificationClient>, ComposerClassFactory falls through to FakesClassComposer, which constructs the Fake<T> on demand.
  3. When the suite's IZeClassFactory completes, AutofacContainerClassComposer.Dispose() tears down the Autofac ILifetimeScope and root IContainer automatically.

Multiple Modules

Both [AutofacModule] and [AutofacContainer] support AllowMultiple = true, allowing multiple Autofac Module types to be composed onto the same test class.