I want to replace existing registered instances in Autofac with new ones in ASP.NET MVC application in runtime. Registrations are keyed as I work with collections of instances of different subtype, though it seems to be irrelevant to my issue.
Initial registration on application startup
foreach (var instance in instances)
{
builder.RegisterInstance(instance).Keyed<IInstance>(InstanceType.A);
}
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
Further on, in a controller method I do the following: dispose old instances, obtain new ones, create a new builder, reregister existing components and also register new instances, then update Autofac's ComponentContext
//...dispose old instances, obtain new instances
var builder = new ContainerBuilder();
foreach (var c in _componentContext.ComponentRegistry.Registrations)
{
builder.RegisterComponent(c);
}
foreach (var instance in newInstances)
{
builder.RegisterInstance(instance).Keyed<IInstance>(InstanceType.A);
}
builder.Update(_componentContext.ComponentRegistry);
Next time I enter the controller method, in controller constructor the old instances are resolved as IIndex<InstanceType, IInstance[]>, not the new ones. What am I doing wrong?