AutoMapper and ASP. net mvc. Generally, AutoMapper is used in the Controller Action to convert the Presentation Model passed by the front-end to the Entity Model in the corresponding business logic. if you write AutoMapper in the Action. createMap <T1, T2>, the Code does not have much to do with the business logic, so it should not be written in Action. We can use the Filter feature in ASP. net mvc to complete the configuration before performing AutoMapper conversion in the Action in the form of a Filter.
First, define a MyProfile, inherit from the Profile class of AutoMapper, and override the Configure () method to Configure it in this method.
[Csharp]
Public class OrderDomainMvcProfile: Profile
{
Public override string ProfileName
{
Get {return "OrderDomainMvcProfile ";}
}
Protected override void Configure ()
{
// Map ......
Mapper. CreateMap <T1, T2> (). ForMember (......);
}
}
Public class OrderDomainMvcProfile: Profile
{
Public override string ProfileName
{
Get {return "OrderDomainMvcProfile ";}
}
Protected override void Configure ()
{
// Map ......
Mapper. CreateMap <T1, T2> (). ForMember (......);
}
} Then load the data in the Filter.
[Csharp]
[AttributeUsageAttribute (AttributeTargets. Class | AttributeTargets. Method, Inherited = false, AllowMultiple = false)]
Public class AutoMapperConfigurationActionFilterAttribute: FilterAttribute
{
Public AutoMapperConfigurationActionFilterAttribute (Type profileType)
{
Mapper. Configuration. AddProfileThreadSafe (Activator. CreateInstance (profileType) as Profile );
}
}
[AttributeUsageAttribute (AttributeTargets. Class | AttributeTargets. Method, Inherited = false, AllowMultiple = false)]
Public class AutoMapperConfigurationActionFilterAttribute: FilterAttribute
{
Public AutoMapperConfigurationActionFilterAttribute (Type profileType)
{
Mapper. Configuration. AddProfileThreadSafe (Activator. CreateInstance (profileType) as Profile );
}
} Finally, apply the Filter to the Action of the Controller.
[Csharp]
[AutoMapperConfigurationActionFilter (typeof (OrderDomainMvcProfile)]
Public virtual ActionResult OrderGrid_Select (GridCommand command)
{......
}
[AutoMapperConfigurationActionFilter (typeof (OrderDomainMvcProfile)]
Public virtual ActionResult OrderGrid_Select (GridCommand command)
{......
}
Another special method is introduced here. I want to complete all the configurations once and for all when the application is started, that is, Application_Start. If ASP. net mvc has multiple domains that correspond to multiple areas, you need to write a lot of code to configure AutoMapper in Application_Start in global. asax. cs. Here we use reflection to find the methods that implement the IStartupTask interface in the DLL, and then run the Excecute method.
Create an IStartupTask Interface
[Csharp]
Public interface IStartupTask
{
Void Execute ();
}
Public interface IStartupTask
{
Void Execute ();
} Implement this interface
[Csharp]
Public class AutoMapperStartupTask: IStartupTask
{
Public void Execute ()
{
Create <User, UserModel> ();
Create <Widget, WidgetModel> ();
Create <WidgetDefinition, WidgetDefinitionModel> ();
// Mapper. CreateMap <ModuleDefinition, ModuleDefinitionModel> ()
//. ForMember (m => m. AppId, o => o. MapFrom (e => e. App = null? (Int ?) Null: e. App. Id ))
//. ForMember (m => m. AppTitle, o => o. MapFrom (e => e. App = null? Null: e. App. Title ));
// Mapper. CreateMap <ModuleDefinitionModel, ModuleDefinition> ();
}
Protected virtual void Create <T1, T2> ()
{
Mapper. CreateMap <T1, T2> ();
Mapper. CreateMap <T2, T1> ();
}
}
Public class AutoMapperStartupTask: IStartupTask
{
Public void Execute ()
{
Create <User, UserModel> ();
Create <Widget, WidgetModel> ();
Create <WidgetDefinition, WidgetDefinitionModel> ();
// Mapper. CreateMap <ModuleDefinition, ModuleDefinitionModel> ()
//. ForMember (m => m. AppId, o => o. MapFrom (e => e. App = null? (Int ?) Null: e. App. Id ))
//. ForMember (m => m. AppTitle, o => o. MapFrom (e => e. App = null? Null: e. App. Title ));
// Mapper. CreateMap <ModuleDefinitionModel, ModuleDefinition> ();
}
Protected virtual void Create <T1, T2> ()
{
Mapper. CreateMap <T1, T2> ();
Mapper. CreateMap <T2, T1> ();
}
}
Introduce all AutoMapper configurations at one time in Global. ascx
[Csharp]
Protected void Application_Start ()
{
......
ExecuteStartupTasks ();
}
Private void ExecuteStartupTasks ()
{
List <IStartupTask> startupTasks = new List <IStartupTask> ();
Assembly asm = this. ExecutingAssembly;
// Get path of executing (bin) folder from the current executing assembly
String codeBase = this. ExecutingAssembly. CodeBase;
UriBuilder uri = new UriBuilder (codeBase );
String path = Uri. UnescapeDataString (uri. Path );
String bin = Path. GetDirectoryName (path );
String [] assemblies = Directory. GetFiles (bin, "*. dll ");
Foreach (String file in assemblies)
{
Try
{
If (File. Exists (file ))
{
// Load the assembly
Asm = Assembly. LoadFrom (file );
// Get all types from the assembly that inherit IStartupTask
Var query = from t in asm. GetTypes ()
Where t. IsClass & t. GetInterface (typeof (IStartupTask). FullName )! = Null
Select t;
// Add types to list of startup tasks
Foreach (Type type in query)
{
StartupTasks. Add (IStartupTask) Activator. CreateInstance (type ));
}
}
}
Catch (Exception ex)
{
Exceptions. LogException (ex );
}
}
// Execute each startup task
Foreach (IStartupTask task in startupTasks)
{
Task. Execute ();
}
}