Run-time registration with Autofac

北城余情 提交于 2019-12-13 11:52:37

问题


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!


回答1:


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.




回答2:


Update for Autofac 4.8.1.0

ContainerBuilder.Update method is marked as Obsolete with a comment:
Containers should generally be considered immutable. Register all of your dependencies before building/resolving. If you need to change the contents of a container, you technically should rebuild the container. This method may be removed in a future major release.



来源:https://stackoverflow.com/questions/6173566/run-time-registration-with-autofac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!