Resolve IContainer

戏子无情 提交于 2019-11-26 12:05:07

问题


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?


回答1:


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.

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

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.

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.



来源:https://stackoverflow.com/questions/4609360/resolve-icontainer

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