可以在Autofac容器中临时注册组件吗? [英] Can components be temporarily registered in an Autofac container?

查看:61
本文介绍了可以在Autofac容器中临时注册组件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为第3方应用程序构建一个插件,并且我的插件使用Autofac连接各种组件.该容器是在应用程序启动时构建的,但是宿主应用程序稍后会调用我的命令.

I'm building a plugin for a 3rd party application and my plugin uses Autofac to wire up various components. The container is built at application startup, but the host application invokes my commands at a later time.

调用命令时,主机应用程序会提供一些它定义的类型的实例,而我的组件将需要使用这些实例.我想在容器中注册这些实例,以便它可以处理依赖于这些实例的组件的连接.

When a command is invoked, the host application provides a few instances of types that it defines and that my components will need to use. I'd like to register these instances in the container so that it can take care of wiring up the components that depend on these instances.

我知道我可以使用ContainerBuilder来更新现有的容器,但是我想在命令完成后删除这些注册,因为这些实例将不再有效.这可能吗?

I'm aware that I can use a ContainerBuilder to update an existing container, but I'd like to remove these registrations when the command has completed as these instances will no longer be valid. Is this possible?

也许更好的方法是使用2个容器...该命令可以创建一个新的容器来注册这些实例,并且其他组件可以从应用程序作用域的容器中解析.

Maybe a better approach is to use 2 containers... The command could create a new container to register these instances and other components could be resolved from the application scoped container.

我该如何连接2个容器,以使解析调用冒泡到应用程序范围的容器?

How could I hook up the 2 containers so that resolve calls bubble up to the application scoped container?

这种方法有什么要注意的地方吗?我想可能存在组件寿命问题...

Are there any gotchas to be aware of with this approach? I imagine there may be component lifetime issues...

现在,我已经进行了更多的研究和测试,事实证明,我可以使用BeginLifetimeScope(Action< ContainerBuilder>)重载来注册主机应用程序提供的实例,仅嵌套生命周期.出于某种原因,我认为将注册添加到嵌套生命周期中会导致将它们添加到根容器中,但事实并非如此.

Now I've done a bit more research and testing and and it turns out I can just use the BeginLifetimeScope(Action<ContainerBuilder>) overload to register the host application provided instances for the nested lifetime only. For some reason I thought that adding registrations to the nested lifetime would result in them being added to the root container but that doesn't seem to be the case.

推荐答案

如我上面的编辑所述,事实证明BeginLifetimeScope(Action< ContainerBuilder>)正是我所需要的.出于某种原因,我认为将注册添加到嵌套生命周期中会导致将它们添加到根容器中,因此在嵌套生命周期作用域结束后可以解析,但是事实并非如此.

As noted in my edit above, it turns out that BeginLifetimeScope(Action<ContainerBuilder>) is exactly what I need. For some reason I thought that adding registrations to the nested lifetime would result in them being added to the root container and therefore being resolvable after the nested lifetime scope ends, but that doesn't seem to be the case.

这篇关于可以在Autofac容器中临时注册组件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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