Now with .NET Core support!
Be a hero! Cleaner configuration for AutoMapper! Just implement one of the mapping interfaces in your view model, and you're set!
Note that you can use Heroic.AutoMapper with any type of project. It no longer depends on ASP.NET!
Install via nuget:
PM> Install-Package Heroic.AutoMapper
Just call HeroicAutoMapperConfigurator.Configure
during your application's startup.
For "classic" versions of ASP.NET, you should call HeroicAutoMapperConfigurator
in your Global.asax
:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
HeroicAutoMapperConfigurator.LoadMapsFromAssemblyContainingTypeAndReferencedAssemblies<HomeController>();
}
}
For a simple console application, you might do something like this:
using Heroic.AutoMapper;
public class Program
{
public static void Main()
{
HeroicAutoMapperConfigurator.LoadMapsFromCallerAndReferencedAssemblies();
Console.WriteLine("All set!");
}
}
For an ASP.NET Core application, you should configure Heroic.AutoMapper in your Startup class, like so:
//..
using Heroic.AutoMapper;
namespace YourNamespace
{
public class Startup
{
//.. snip
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
app.UseAuthentication();
app.UseMvc();
HeroicAutoMapperConfigurator.LoadMapsFromAssemblyContainingTypeAndReferencedAssemblies<WidgetModel>();
}
}
}
Want to map your view model from a domain model? Just implement the IMapFrom<T> interface!
public class CustomerRiskViewModel : IMapFrom<Risk>
{
public string Title { get; set; }
public string Description { get; set; }
}
Need to map a model back to your domain instead? You can implement IMapTo<T> instead:
public class AddCustomerForm : IMapTo<Customer>
{
[Required, Display(Name = "Full Name", Prompt = "Full Name (ex: John Doe)...")]
public string Name { get; set; }
[Required, DataType(DataType.EmailAddress)]
public string WorkEmail { get; set; }
}
But what if you need to customize your mappings? Implement IHaveCustomMappings instead:
public class ProfileForm : IMapFrom<User>, IHaveCustomMappings
{
public string FullName { get; set; }
public string EmailAddress { get; set; }
public void CreateMappings(IMapperConfiguration configuration)
{
configuration.CreateMap<User, ProfileForm>()
.ForMember(d => d.FullName, opt => opt.MapFrom(s => s.UserName))
.ForMember(d => d.EmailAddress, opt => opt.MapFrom(s => s.Email));
}
}
Check out the rest of the Heroic Framework!