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!
You register components with Autofac by creating a ContainerBuilder and informing the builder which components expose which services. Components can be created via reflection (by registering a specific .
You need to exactly write like this: builder. RegisterGeneric(typeof(RepositoryBase<>)) . As(typeof(IRepository<>)); note the empty <> and it will register your Repository for all of your entites.
From Visual Studio, you can get it via NuGet. The package name is Autofac. Alternatively, the NuGet package can be downloaded from the GitHub repository (https://github.com/autofac/Autofac/releases).
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.
Update July 2021 - Autofac has removed the Update method (not recently but I've just noticed). See this issue on github for 'better' ways to do what you want without Update. https://github.com/autofac/Autofac/issues/811
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With