dan*_*wig 4 reflection asp.net-mvc auto-registration automapper automapper-2
在MVC中创建控制器时,您无需为其进行任何其他注册.添加区域也是如此.只要您的global.asax具有AreaRegistration.RegisterAllAreas()调用,就不需要进行其他设置.
使用AutoMapper,我们必须使用某种CreateMap<TSource, TDestination>调用来注册映射.可以使用static显式地执行这些操作Mapper.CreateMap,或者通过从AutoMapper.Profile类派生,重写Configure方法,然后CreateMap从那里调用.
在我看来,应该能够扫描一个程序集,从Profile类似MVC扫描扩展的类扩展Controller.使用这种机制,不应该仅通过创建派生自的类来创建映射Profile吗?是否存在任何此类库工具,或者是否存在内置于automapper中的内容?
我不知道这样的工具是否存在,但写一个应该是非常简单的:
public static class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(x => GetConfiguration(Mapper.Configuration));
}
private static void GetConfiguration(IConfiguration configuration)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
var profiles = assembly.GetTypes().Where(x => x != typeof(Profile) && typeof(Profile).IsAssignableFrom(x));
foreach (var profile in profiles)
{
configuration.AddProfile((Profile)Activator.CreateInstance(profile));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的Application_Start你可以autowire:
AutoMapperConfiguration.Configure();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2180 次 |
| 最近记录: |