解析 IContainer [英] Resolve IContainer

查看:20
本文介绍了解析 IContainer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从应用程序的类内部获取 Autofac 容器的建议方法是什么?Autofac 是否提供解析类上的 IContainer 属性,或者我是否需要在构建容器后将其全局存储?

What is the suggested method of getting the Autofac container from inside a class in the application? Does Autofac provide for resolving an IContainer property on a class or do I need to store the container globally once I've build it?

推荐答案

对于大多数用途,您将需要 IComponentContextILifetimeScope.这些由 Autofac 自动提供,因此您需要做的就是对其中一个建立(构造函数)依赖项,然后将注入当前实例.

You'll need IComponentContext or ILifetimeScope for most purposes. These are automatically provided by Autofac, so all you need to do is take a (constructor) dependency on one of them and the current instance will be injected.

两个接口都提供标准的 Resolve() 操作,而 ILifetimeScope 扩展了 IComponentContext 通过添加方法来启动新的嵌套生命周期.

Both interfaces provide the standard Resolve() operations, while ILifetimeScope extends IComponentContext by adding methods for starting new nested lifetimes.

想要使用容器的服务来访问其他组件的组件需要在它们自己的范围内这样做,而不是'全局'IContainer,这样才能返回正确的实例.例如.在 HTTP 请求中,注入的 IComponentContextILifetimeScope 将是当前请求的那个.

Components that want to use the services of the container to access other components need to do so within their own scope, rather than the 'global' IContainer, so that the correct instance can be returned. E.g. within an HTTP request, the injected IComponentContext or ILifetimeScope will be the one for the current request.

大多数需要注入上下文的问题也可以(通常更优雅地)使用关系类型来克服 - 请参阅:http://autofac.readthedocs.org/en/latest/resolve/relationships.html.

Most problems that require an injected context can also be (often more elegantly) overcome using Relationship Types - see: http://autofac.readthedocs.org/en/latest/resolve/relationships.html.

这篇关于解析 IContainer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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