Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save misha130/41a7cf6c75f2d2495a6be41ebe69ac35 to your computer and use it in GitHub Desktop.
Save misha130/41a7cf6c75f2d2495a6be41ebe69ac35 to your computer and use it in GitHub Desktop.
// Service Registration
services.AddSingleton(provider => new MapperConfiguration(cfg =>
{
var profiles = typeof(Startup).Assembly.GetTypes()
.Where(t => t.BaseType == typeof(Profile) && !t.IsAbstract && t.IsPublic);
var serviceFactory = provider.GetService<IServiceScopeFactory>();
foreach (var profile in profiles)
{
var profileInstance = Activator.CreateInstance(profile, serviceFactory) as AutoMapper.Profile;
cfg.AddProfile(profileInstance);
}
}).CreateMapper());
// Profile Example
public class WeatherProfile : Profile
{
public WeatherProfile(IServiceScopeFactory serviceFactory)
{
using (var scope = serviceFactory.CreateScope())
{
var forecastService = scope.ServiceProvider.GetRequiredService<WeatherService>();
CreateMap<int, WeatherForecast>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment