如何在.Net 4.7.1 WebApi项目中配置AutoMapper 9

时间:2019-12-20 06:49:13

标签: configuration automapper

我正在尝试在.Net 4.7.2应用程序中配置Automapper v9,但无法使其正常工作。我知道我对此会有些悲痛,但是Automapper上针对新手的文档太可怕了。

文档显示了这样的代码,但是没有说明如何在应用程序中实现它。我确定我不应该将此代码添加到每个控制器中。

var config = new MapperConfiguration(cfg => {
cfg.AddProfile<AppProfile>();
cfg.CreateMap<Source, Dest>();
});

var mapper = config.CreateMapper();
// or
IMapper mapper = new Mapper(config);
var dest = mapper.Map<Source, Dest>(new Source());

这是我可以从文档中收集到的信息,但是我意识到我可能还差得远。

我的个人资料配置文件:

    public class AutoMapperProfile : Profile
    {
        public override string ProfileName { get { return "AutoMapperProfile"; } }

        protected void Configure()
        {
            CreateMap<GolfClub, GolfClubDto>().ReverseMap();
        }
    }

这是我的映射器配置文件:

    public class AutoMapperConfiguration
    {
        public static MapperConfiguration Configure()
        {
            var config = new MapperConfiguration(cfg => cfg.AddProfile(new AutoMapperProfile()));

            return config;
        }
    }

然后将其应用于Global.asax:

    public class WebApiApplication : HttpApplication
    {
        public MapperConfiguration autoMapperConfig;

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            autoMapperConfig = AutoMapperConfiguration.Configure();
        }
    }

然后终于在我的WebApi控制器中,我在Get方法中拥有它:

        [HttpGet()]
        [Route("api/golf")]
        public GetGolfClubListResponse Get()
        {
            GetGolfClubListResponse response = new GetGolfClubListResponse();

            try
            {
                var entities = golfClubService.Get(null, null, "GolfCourseList").ToList();

                var mapper = WebApiApplication.autoMapperConfig.CreateMapper();  // Error here

                var dtos = mapper.Map<List<GolfClubDto>>(entities);

                response.GolfClubList = dtos;
                response.Success = true;

                return response;
            }
            catch (Exception)
            {
                response.Success = false;
                response.Message = "There was a problem getting the list of golf clubs.";
                return response;
            }
        }

在autoMapperConfig.CreateMapper()行上出现的红色弯曲错误是:

An object reference is required for the non-static field, method or property "WebApiApplication.autoMapperConfig".

我知道这是错误的,但是我不知道该如何做。有人可以帮我弄清楚在项目中配置Automapper 9的正确方法吗?

0 个答案:

没有答案