尝试将 Autofac DI 与 Sitecore 8.2 一起使用时出现以下错误:
The dependency resolver is of type 'Sitecore.Mvc.Controllers.SitecoreDependencyResolver' but was expected to be of type 'Autofac.Integration.Mvc.AutofacDependencyResolver'. It also does not appear to be wrapped using DynamicProxy from the Castle Project. This issue could be the result of a change in the DynamicProxy implementation or the use of a different proxy library to wrap the dependency resolver.
任何想法:
- 为什么会出现这种情况?
- 以上是什么意思?
- 如何解决?
最佳答案
问题的根源
发生这种情况是因为 AutofacDependencyResolver
不是 MVC 当前的依赖解析器。以下是 AutofacDependencyResolver.Current
如何尝试定位其自身的当前实例的描述:
http://docs.autofac.org/en/latest/integration/mvc.html#using-the-current-autofac-dependencyresolver
因此您需要使用 MVC 设置 AutofacDependencyResolver
。通常,您只需遵循本指南:
http://docs.autofac.org/en/latest/integration/mvc.html#quick-start
不过,这可能是您已经在做的事情。问题是,在某些时候,Sitecore 会用自己的依赖项解析器覆盖已配置的依赖项解析器,这会在 Application_Start
执行后发生。所以 AutofacDependencyResolver
最终没有被 MVC 使用。
如何修复
遵循本指南:
http://www.seanholmesby.com/safe-dependency-injection-for-mvc-and-webapi-within-sitecore/
它的本质是你需要创建一个自定义依赖解析器,它将首先使用 AutofacDependencyResolver
,如果没有找到依赖,它将回退到 SitecoreDependencyResolver
。
依赖解析器应配置为 Sitecore 的 initialize
管道中的处理器,这将确保 Sitecore 的依赖解析器已经可用。
您可以在这个 GitHub 存储库中找到特定于 Autofac 的示例:
覆盖 Autofac 的依赖解析器访问器
如果以上方法没有帮助,您可以告诉 Autofac 如何获取当前的解析器。
当您创建 Autofac 解析器时,将该对象保存在一个变量中,一旦您在 MVC 中注册了链式解析器,请使用方法 AutofacDependencyResolver.SetAutofacDependencyResolverAccessor()
:
var autofacResolver = new AutofacDependencyResolver(container);
IDependencyResolver chainedMvcResolver = new ChainedMvcResolver(
autofacResolver,
DependencyResolver.Current);
DependencyResolver.SetResolver(chainedMvcResolver);
AutofacDependencyResolver.SetAutofacDependencyResolverAccessor(() => autofacResolver);
现在 Autofac 不会尝试直接在 DependencyResolver.Current
或 CaSTLe 的 DynamicProxy 中寻找自己的解析器。它将直接使用您提供的解析器对象。
关于dependency-injection - Sitecore 8.2 Autofac 依赖注入(inject)错误说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39541270/