Вы можете использовать профиль для создания всех картографов, перейдя по этой ссылке http://docs.automapper.org/en/stable/Configuration.html
Другой подход, который вы можете инициализировать в статическом конструкторе - все отображения, которые вы хотите, используя некоторые соглашения об именах
В приведенном ниже коде я отображаю один и тот же тип объекта на тот же тип объекта
// Data or View Models
public class AddressViewModel : BaseViewModel
{
public string Address {get;set;}
public AddressViewModel()
{
this.Address ="Address";
}
}
public class UserViewModel : BaseViewModel
{
public string Name {get;set;}
public UserViewModel()
{
this.Name ="Name";
}
}
public class BaseViewModel
{
}
Репозиторий - здесь я использую ту же модель представления, вы должны создать здесь Модели
public class CrudRepo
{
public IEnumerable<T> GetData<T>() where T : class, new ()
{
var data = new List<T> { new T() };
return AutoMapper.Mapper.Map<IEnumerable<T>>(data);
}
}
Затем в статическом конструкторе инициализировать преобразователи
static HelperClass()
{
// In this case all classes are present in the current assembly
var items = Assembly.GetExecutingAssembly()
.GetTypes().Where(x =>
typeof(BaseViewModel)
.IsAssignableFrom(x))
.ToList();
AutoMapper.Mapper.Initialize(cfg =>
{
items.ForEach(x =>
{
// Here use some naming convention or attribute to find out the Source and Destination Type
//Or use a dictionary which gives you source and destination type
cfg.CreateMap(x, x);
});
});
}
Теперь вы можете создать экземпляр репозитория crud и получить сопоставленные элементы
var userRepo = new CrudRepo();
var users = userRepo.GetData<UserViewModel>();
var address = addressRepo.GetData<AddressViewModel>();
Note
: Пока имена и типы свойств совпадают, данные будут отображаться, иначе вам придется создавать ForMember