Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run-time registration with Autofac

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!

like image 435
Daniel Miller Avatar asked May 30 '11 07:05

Daniel Miller


People also ask

How do I register Autofac services?

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 .

How do I register a generic repository in Autofac?

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.

How do I get Autofac containers?

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).


1 Answers

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

like image 176
bentayloruk Avatar answered Sep 25 '22 17:09

bentayloruk