c# - 映射器未初始化,使用 ProjectTo() 时

标签 c# ioc-container structuremap automapper-5

我在我的项目中使用 Automapper 5.2.0。当我在代码中使用 ProjectTo() 时出现此错误:

Mapper not initialized. Call Initialize with Appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.

服务代码

 public async Task<FreelancerProfileViewModel> GetFreelancerProfile()
    {
        var id = Guid.Parse(_identity.GetUserId());
        var model = await _freelancerProfiles
            .AsNoTracking()
            .Where(_ => _.User.Id == id)
            .ProjectTo<FreelancerProfileViewModel>()
            .FirstAsync();

     //  var viewmodel =  _mapper.Map<FreelancerProfileViewModel>(model);

        return model;
    }

Automapper 配置文件

   public class FreelancerDashbordProfile : Profile
{
    private readonly IIdentity _identity;
    public FreelancerDashbordProfile(IIdentity identity)
    {
        _identity = identity;
        var id = Guid.Parse(_identity.GetUserId());
        CreateMap<FreelancerProfile, FreelancerProfileViewModel>()
        .ForMember(_ => _.DoingProjectCount,
            __ => __.MapFrom(_ => _.Projects.Count(project => project.ProjectState == ProjectState.Doing)))

        .ForMember(_ => _.EndProjectCount,
            __ => __.MapFrom(_ => _.Projects.Count(project => project.ProjectState == ProjectState.End)))

        .ForMember(_ => _.ProjectCount, __ => __.MapFrom(_ => _.Projects.Count));

    }

}

我也用StructureMap对于 IoC

AutoMapperRegistery

   public AutoMapperRegistery()
    {

        this.Scan(scan =>
        {
            scan.TheCallingAssembly();
            scan.AssemblyContainingType<SkillProfile>(); // for other asms, if any.
            scan.WithDefaultConventions();

            scan.AddAllTypesOf<Profile>().NameBy(item => item.FullName);
        });

        this.For<MapperConfiguration>().Singleton().Use("MapperConfig", ctx =>
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMissingTypeMaps = true; // It will connect `Person` & `PersonViewModel` automatically.
                addAllCustomAutoMapperProfiles(ctx, cfg);
            });
            config.AssertConfigurationIsValid();

            return config;
        });

        this.For<IMapper>()
            .Singleton()
            .Use(ctx => ctx.GetInstance<MapperConfiguration>().CreateMapper(ctx.GetInstance));


    }

我看到其他 QuestionIssue但没有解决我的问题。

最佳答案

您需要将 MappingConfiguration 提供程序传递给 ProjectTo 调用。

public async Task<FreelancerProfileViewModel> GetFreelancerProfile()
{
    var id = Guid.Parse(_identity.GetUserId());
    var model = await _freelancerProfiles
        .AsNoTracking()
        .Where(_ => _.User.Id == id)
        .ProjectTo<FreelancerProfileViewModel>(_mapper.Configuration)
        .FirstAsync();

 //  var viewmodel =  _mapper.Map<FreelancerProfileViewModel>(model);

    return model;
}

关于c# - 映射器未初始化,使用 ProjectTo() 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41961439/

相关文章:

c# - 如何在 c#.net 中以编程方式重启我的窗口服务

c# - 如何使用 C# 从字节数组为 WPF 媒体元素创建源?

c# - 固件 : Unexpected result upon unnamed registration of the same mapTo with different mapFrom with injectedProperties

session - ravendb 长时间运行的 session

.net - 使用 StructureMap 配置 Prism

c# - 如何在 azure 中使用一个(数据库)连接字符串与多个网站

c# - Silverlight 不适用于网络的不同 IP 段

dependency-injection - 有状态对象(非全局)的 IoC 依赖注入(inject)

spring - 在 IoC 容器中创建的对象可以称为 Singleton。如果不是 - 为什么?

asp.net-web-api - 如何在不调用 setter 注入(inject)的情况下丰富 StructureMap 中的对象组合?