You can use scope.ServiceProvider.GetServices<IMongoMapper>();
to get all classes that implement IMongoMapper
interface.
You can use an extension method and call it in Configure
method in startup
class.
public static void IntializeMapping(this IApplicationBuilder app)
{
using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var mappers = scope.ServiceProvider.GetServices<IMongoMapper>();
foreach (var map in mappers)
{
map.Configure();
}
}
}
and use it in startup
class
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.IntializeMapping();
}
Update
According to Microsoft documentation better way is use this
public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
try
{
var mappers = scope.ServiceProvider.GetServices<IMongoMapper>();
foreach (var map in mappers)
{
map.Configure();
}
}
catch (Exception ex)
{
var logger = service.GetService<ILogger<Program>>();
logger.LogError(ex, "An error occurred mapping");
}
}
await host.RunAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Microsoft Documentation
In older tutorials, you may see similar code in the Configure
method in Startup.cs
. We recommend that you use the Configure
method only to set up the request pipeline. Application startup code belongs in the Main method.
Now the first time you run the application, the database will be created and seeded with test data. Whenever you change your data model, you can delete the database, update your seed method, and start afresh with a new database the same way. In later tutorials, you'll see how to modify the database when the data model changes, without deleting and re-creating it.