Asp.net web api AutoFacWebApidencyResolver的使用

Asp.net web api AutoFacWebApidencyResolver的使用,asp.net-web-api,autofac,Asp.net Web Api,Autofac,AutoFacWebApidencyResolver的用途是什么 我是这样设置的: GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); 但是如何在我的ApiControllers中访问它 DependencyResolver.Current不是AutoFacWebAPI DependencyResolver,而是MVC版本 .Cur

AutoFacWebApidencyResolver
的用途是什么

我是这样设置的:

GlobalConfiguration.Configuration.DependencyResolver = 
    new AutofacWebApiDependencyResolver(container);
但是如何在我的
ApiController
s中访问它

DependencyResolver.Current
不是
AutoFacWebAPI DependencyResolver
,而是MVC版本


.Current
可在
AutofacDependencyResolver
下使用,但不能在
autofacWebAPI DependencyResolver
下使用。如何在web api中访问web api版本?

如您所示。。。使用
GlobalConfiguration.Configuration.DependencyResolver
访问此解析程序,方法与最初设置时相同(它是一个静态对象,可以从Web API中的任何位置访问)

或者,使用请求依赖范围-只要您有权访问当前请求(即在
MessageHandler
中):


这将使用当前设置的AutofacWebApiDependencyResolver来解析
IMyService
,正如您所展示的那样。。。使用
GlobalConfiguration.Configuration.DependencyResolver
访问此解析程序,方法与最初设置时相同(它是一个静态对象,可以从Web API中的任何位置访问)

或者,使用请求依赖范围-只要您有权访问当前请求(即在
MessageHandler
中):


这将使用当前设置的AutofacWebApiDependencyResolver解决
IMyService

尝试简单的方法:
this.Configuration.DependencyResolver
,其中,
是一个
ApiController
实例。

请尝试简单的方法:
此.Configuration.DependencyResolver
,其中,
是一个
ApiController
实例。

好的,谢谢。但这似乎只适用于网络托管。我使用自托管,并且总是为空。或者此错误:无法创建请求生存期范围,因为HttpContext不可用。autofac不能支持自托管吗?顺便说一句:这是AutofacWebApidentiencyResolver的优点。我可以设置AutofacDependencyResolver并使用它。AutofacWebApiDependencyResolver可以做更多的工作吗?@user437899您能否提供有关从何处获取null以及引发异常的方法的详细信息?好的,谢谢。但这似乎只适用于网络托管。我使用自托管,并且总是为空。或者此错误:无法创建请求生存期范围,因为HttpContext不可用。autofac不能支持自托管吗?顺便说一句:这是AutofacWebApidentiencyResolver的优点。我可以设置AutofacDependencyResolver并使用它。AutofacWebApiDependencyResolver可以做更多的工作吗?@user437899能否提供有关从何处获取null以及引发异常的方法的详细信息?我建议您不要这样做。Autofac旨在以依赖项注入的方式使用,而不是以服务定位器的方式使用。只需使用构造函数或属性注入来获取依赖项。我建议您不要这样做。Autofac旨在以依赖项注入的方式使用,而不是以服务定位器的方式使用。只需使用构造函数或属性注入即可获得依赖项。
var myservice = request.GetDependencyScope().GetService(typeof(IMyService)) as IMyService