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:
AutofacContainerClassComposerusesscope.ResolveOptional(args)forIPricingServiceandOrderValidator, returning real container-managed instances.- When Autofac returns
nullforFake<INotificationClient>,ComposerClassFactoryfalls through toFakesClassComposer, which constructs theFake<T>on demand. - When the suite's
IZeClassFactorycompletes,AutofacContainerClassComposer.Dispose()tears down the AutofacILifetimeScopeand rootIContainerautomatically.
Multiple Modules
Both [AutofacModule] and [AutofacContainer] support AllowMultiple = true, allowing multiple Autofac Module types to be composed onto the same test class.