ComponentNotRegisteredException 使用 AutoMapper 和 Autofac

问题描述 投票:0回答:0

尝试解析

AutoMapper.IMapper
实例时出现错误:

Autofac.Core.Registration.ComponentNotRegisteredException:请求的服务“System.Object”尚未注册。

这是我的注册:

Builder.Register(Function(Context)
                   Return New MapperConfiguration(Sub(Config)
                                                    Config.AddProfile(Of MappingProfile)()
                                                  End Sub).CreateMapper
                 End Function).As(Of IMapper)()

...这是解决方案:

Using oScope As ILifetimeScope = Me.Container.BeginLifetimeScope
  oMapper = oScope.Resolve(Of IMapper)
End Using

这是我的地图配置文件:

Public Class MappingProfile
  Inherits Profile

  Public Sub New()
    Me.CreateMap(Of Dto.Release, Model.Release)()
    Me.CreateMap(Of Model.Release, Dto.Release)()
  End Sub
End Class

我已经尝试了这些答案和更多的建议,但除了更复杂的错误之外,它们都没有导致任何结果:

...以及这篇博文.

我在这里发现了很多关于将 AutoMapper 与 Autofac 结合使用的问答,其中很多都有公认的答案,但似乎没有一个适用于我的情况(至少我能够理解/识别)。但话又说回来,这里关于一起使用两者的讨论已经过时了。在最新版本的上下文中,搜索中出现的内容并不多。

我确实注意到一些已接受的答案中的一种模式,那就是将

Func(Of Object, IMapper)
传递给
Builder.Register()
函数。也许这就是错误的来源:
Object
类型的参数
Func
.

值得注意的是这里的

Context
参数——至少对我来说——总是类型
System.Object
:

Builder.Register(Function(Context)
                 End Function)

所以我没有看到人们如何让这样的代码工作:

builder.Register(c =>
{
  //This resolves a new context that can be used later.
  var context = c.Resolve<IComponentContext>();
})

显然

Resolve<IComponentContext>()
上没有
System.Object
功能。自从编写这些答案以来,Autofac API 中关于
Builder.Register()
函数的内容是否发生了变化?

假设使用两个包的最新版本,我如何才能成功注册和解析

AutoMapper.IMapper
实例?

automapper autofac
© www.soinside.com 2019 - 2024. All rights reserved.