Autofac now supports this out of the box with an extension to the lifetime scopes. The BeginLifetimeScope()
method has an overload that takes an Action<ContainerBuilder>
that allows for adding new registrations specific to only that lifetime scope. So for the given example it would look something like:
var builder = new ContainerBuilder();
builder.RegisterType<MyService>().As<IMyService>().InstancePerLifetimeScope();
var container = builder.Build();
using(var scope = container.BeginLifetimeScope(
builder =>
{
builder.RegisterInstance(new Data(....));
}))
{
// References to 'IMyService' will always be resolved to the same instance within this lifetime scop
// References to 'Data' will be resolved to the instance registered just for this lifetime scope.
var svc = scope.Resolve<IMyService>();
}