我有一个3层架构Web Api解决方案,里面有3个项目:数据,业务和表示层。我需要在两个业务和表示层中初始化两个不同的映射器。
我已经创建了一个静态类和方法来初始化业务逻辑中的一个映射器:
using AutoMapper;
using Shop.BLL.DTOModels;
using Shop.DAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shop.BLL.InitMapper
{
public static class InitializeMapperBLL
{
public static void RegisterMappings()
{
Mapper.Initialize(cfg => cfg.CreateMap<Category, DTOCategoryModel>());
}
}
}
并称之为:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Shop.DAL.Repositories;
using AutoMapper;
using Shop.BLL.DTOModels;
using Shop.DAL.Models;
using Shop.BLL.Interfaces;
using Shop.DAL.Interfaces;
using Shop.BLL.InitMapper;
namespace Shop.BLL.Services
{
public class CategoryService : ICategoryService
{
IUnitOfWork Database { get; set; }
public CategoryService(IUnitOfWork uow)
{
Database = uow;
}
public IEnumerable<DTOCategoryModel> GetCategories()
{
//I call it here
InitializeMapperBLL.RegisterMappings();
return Mapper.Map<IEnumerable<Category>, List<DTOCategoryModel>>(Database.Categories.GetAll());
}
public void Dispose()
{
Database.Dispose();
}
}
}
在表示层我做同样的事情:
using AutoMapper;
using Shop.API.ViewModels;
using Shop.BLL.DTOModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shop.API.MapperInit
{
public static class InitializeMapperAPI
{
public static void RegisterMappings()
{
Mapper.Initialize(cfg => cfg.CreateMap<DTOCategoryModel, CategoryViewModel>());
}
}
}
并调用Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//here I call it
InitializeMapperAPI.RegisterMappings();
CreateKernel();
}
我已经初始化了错误Mapper。您必须为每个应用程序域/进程调用一次Initialize。
如何解决这个问题呢?