使用Autofac进行运行时注册 [英] Run-time registration with Autofac

查看:135
本文介绍了使用Autofac进行运行时注册的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与同事讨论Autofac时,出现了依赖项的运行时注册问题.例如,在Prism中,程序集会在运行时频繁加载,并将其依赖项注册到IoC容器(通常是Unity)中.

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

如何使用Autofac做到这一点?

How can this be accomplished with Autofac?

根据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?

(请注意,程序集可能希望添加依赖项以供应用程序中其他组件的使用,因此嵌套容器可能无法在此处解决问题.与该主题相关:Unity具有诸如RegisterIfExists之类的方法.有Autofac等效项吗?)

(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?)

谢谢!

推荐答案

更新现有的Autofac容器:您可以在运行时使用ContainerBuilder.Update()更新现有的Autofac Container.以下代码示例摘自博客文章 Autofac 2.2已发布 ,演示用法:

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和Prism集成:问题 Prism在Autofac中的集成状态如何?可能对您也有用.

Autofac and Prism Integration: The question Whats the status of Prism integration in Autofac? may also be useful to you.

这篇关于使用Autofac进行运行时注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆