Reputation: 85
I have a .Net Core project where I Configured different options. Now it looks more complex, so I need to split each in to different methods.
For Example I registered mongo db credentials options and I need to move this to simple extension methods:
services.Configure<DataAccess.MongoDB.Contracts.AppSettings.MongoDBSettings> options =>
{
options.ConnectionString
= GetConfigurationSection("MongoConnection:ConnectionString");
options.Database
= GetConfigurationSection("MongoConnection:Database");
});
Expected something like this:
services.ConfigureMongoDbSettings();
Upvotes: 1
Views: 400
Reputation: 25351
Move your code to a class like this (you can name it whatever you like):
public static class MongoDbSettingsCollectionExtensions {
public static IServiceCollection ConfigureMongoDbSettings(
this IServiceCollection services,
IConfiguration Configuration) {
services.Configure<DataAccess.MongoDB.Contracts.AppSettings.MongoDBSettings> options =>
{
options.ConnectionString
= Configuration.GetConfigurationSection("MongoConnection:ConnectionString");
options.Database
= Configuration.GetConfigurationSection("MongoConnection:Database");
});
return services;
}
}
This will allow you to call it in Startup
as you suggested:
services.ConfigureMongoDbSettings(Configuration);
Alternatively, you can pass it the configuration section itself which is what the Core team did with some services:
services.ConfigureMongoDbSettings(Configuration.GetConfigurationSection("MongoConnection"));
Obviously, in this way you'll have to change the ConfigureMongoDbSettings()
function above to receive and work directly with the configuration section.
Upvotes: 1