If you register them all as InstancePerDependency, you can't do what
you're trying to do (to the best of my knowledge). You can, however,
do what you want through the judicious use of lifetime scopes.
For example, register the services as InstancePerLifetimeScope:
var builder = new ContainerBuilder();
builder.RegisterType<ServiceA>().As<IServiceA>().InstancePerLifetimeScope();
builder.RegisterType<ServiceB>().As<IServiceB>().InstancePerLifetimeScope();
builder.RegisterType<ServiceC>().As<IServiceC>().InstancePerLifetimeScope();
var container = builder.Build();
Then before you resolve your services, create a new lifetime scope
like this:
IServiceC resolved1 = null;
using (var scope = container.BeginLifetimeScope())
{
resolved1 = scope.Resolve<IServiceC>();
}
This will ensure that, just for this resolution of the IServiceC
instance, all of the IServiceA instances will be the same.
For testing purposes, I added some public properties to the classes so
I could access the instances getting set and this tests out:
IServiceC resolved1 = null;
using (var scope = container.BeginLifetimeScope())
{
resolved1 = scope.Resolve<IServiceC>();
Assert.AreSame(resolved1.A, resolved1.B.A);
}
IServiceC resolved2 = null;
using (var scope = container.BeginLifetimeScope())
{
resolved2 = scope.Resolve<IServiceC>();
Assert.AreSame(resolved1.A, resolved1.B.A);
}
Assert.AreNotSame(resolved1, resolved2);
Hope that helps,
-T