gpt4 book ai didi

c# - 通用映射器而不是有许多单独的映射器

转载 作者:行者123 更新时间:2023-11-30 19:19:55 24 4
gpt4 key购买 nike

我将 ASP.NET MVC 3RazorAutofac 一起用于依赖项注入(inject)。

我正在考虑创建一个通用映射器。目前我正在使用 AutoMapper 来映射我的域和 View 模型。它可以是任何映射框架,但我使用的是 AutoMapper 。

这是我的 IMapper 界面:

public interface IMapper
{
object Map(object source, Type sourceType, Type destinationType);
}

然后我有一个实现此 IMapper 接口(interface)的 IBankMapper 接口(interface)。我这样做的原因是因为我可以有很多不同的映射器。使用依赖注入(inject)我可以知道我可以注入(inject)什么实例。因此,对于 IBankMapper,我将注入(inject) BankMapper,对于 ICategoryMapper,我将注入(inject) CategoryMapper。

IBankMapper 接口(interface):

public interface IBankMapper : IMapper
{
}

BankMapper 类:

public class BankMapper : IBankMapper
{
static BankMapper()
{
Mapper.CreateMap<Bank, EditBankViewModel>();
Mapper.CreateMap<EditBankViewModel, Bank>();
}

public object Map(object source, Type sourceType, Type destinationType)
{
return Mapper.Map(source, sourceType, destinationType);
}
}

随着程序的增长,映射器类也会增长。有没有一种方法可以创建一个通用映射器,一个可以在整个应用程序中使用的映射器?这可能吗?

最佳答案

您完全不需要创建任何映射器类。

您需要做的就是确保在应用程序开始时调用 Mapper.CreateMap。然后,您可以使用 Mapper.Map 进行映射。

通常,我会创建一个静态类,其中包含一个方法来处理我的 map 的创建。它看起来像:

public static class Transformers
{
public static void Register()
{
Mapper.CreateMap<Bank, EditBankViewModel>();
Mapper.CreateMap<EditBankViewModel, Bank>();

Mapper.CreateMap<Account, EditAccountViewModel>();
Mapper.CreateMap<EditAccountViewModel, Account>();

// And so on. You can break them up into private methods
// if you have too many.
}
}

然后我在 Global.asax 中调用该方法以确保它在必要时运行。在我的应用程序的任何其他位置,我可以为任何已配置的映射自由调用 Mapper.Map:

protected void Application_Start()
{
Transformers.Register();
}

关于c# - 通用映射器而不是有许多单独的映射器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7570047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com