Stu*_*ser 10 .net c# console-application automapper
是否可以 在控制台应用程序中使用automapper?
它的入门页面建议从应用程序启动时调用bootstrapper类,但是没有关于要添加和调用的类的更多详细信息Main().
如何在简单的控制台应用程序中使用它?
lwb*_*lwb 12
我知道这是一个老问题,但如果您发现这个问题,我想添加一个更新:Automaper 不再允许静态初始化。
下面,我提供了如何在控制台应用程序上使用它的完整示例。希望这对将来的人有帮助。
class Program
{
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<MyClass, MyClassDTO>();
});
IMapper mapper = config.CreateMapper();
var myClass = new MyClass(){
Id = 10,
Name = "Test"
};
var dst = mapper.Map<MyClass, MyClassDTO>(myClass);
Console.WriteLine(dst.Id);
}
}
class MyClass
{
public int Id {get;set;}
public string Name {get;set;}
}
public class MyClassDTO
{
public int Id {get;set;}
public string Name {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
不要忘记包括using AutoMapper;
sam*_*amy 10
您可以在控制台启动时初始化Automapper,没有任何限制; Application_start是.net/iis中Web程序的启动位置,即只调用一次的代码.在Web项目开始时必须调用的任何配置都使用此方法.
编辑注释:如果你不想动态创建映射,但宁愿有一个初始化所有映射的地方,只需创建一个调用的函数InitializeAutomapper并Mapper.Configure<X, Y>在此处进行调用.然后在你的Main()方法中,只需调用该函数.有很多方法可以处理配置,但这是处理它的更简单方法.
代码示例
class Program
{
static void Main(string[] args)
{
// the app is starting here
InitializeAutomapper();
// we're configured, let's go!
DoStuff();
}
static void InitializeAutomapper()
{
AutoMapper.Mapper.CreateMap<TypeA, TypeB>();
AutoMapper.Mapper.CreateMap<TypeC, TypeD>();
AutoMapper.Mapper.CreateMap<TypeE, TypeF>();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6116 次 |
| 最近记录: |