While discussing Autofac with a colleague, the issue of run-time registration of dependencies arose. In Prism, for instance, assemblies are frequently loaded at run time and their dependencies registered with the IoC container (usually Unity).
How can this be accomplished with Autofac?
From Autofac's documentation and what I've found on the web, it seems that registration is performed at application start. Even when "external" assemblies are used, the registrations are located in modules with the assemblies at app start. How do we do this after the container is "built" at app start?
(Note that the assembly may want to add dependencies for the use of other components in the application, and so a nested container may not solve the problem here. Related to this topic: Unity has methods such as RegisterIfExists and the like. Are there Autofac equivalents?)
Thanks!
Update an existing Autofac Container: You can update an existing Autofac Container
at runtime by using ContainerBuilder.Update()
. The following code sample, taken from the blog post Autofac 2.2 Released, demonstrates the usage:
var container = // something already built
var updater = new ContainerBuilder();
updater.RegisterType<A>();
updater.Register(c => new B()).As<IB>();
// Add the registrations to the container
updater.Update(container);
Autofac and Prism Integration: The question Whats the status of Prism integration in Autofac? may also be useful to you.