Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created April 19, 2021 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/082b5ce8aba039eb546a6169ac40ecd5 to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/082b5ce8aba039eb546a6169ac40ecd5 to your computer and use it in GitHub Desktop.
Bind configurations to an object
// Class to hold mail feature json object
public class MailFeatureSettings
{
public string Type { get; set; }
public string From { get; set; }
public string Subject { get; set; }
}
// Startup.cs code
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// some code...
// bind config settings to an object
List<MailFeatureSettings> mailFeatureSettings = new List<MailFeatureSettings>();
Configuration.GetSection("MailFeature").Bind(mailFeatureSettings);
// register object in DI container so that it can be injected
services.AddSingleton<IList<MailFeatureSettings>>(mailFeatureSettings);
// some code...
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// some code...
}
}
// HomeController.cs
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IList<MailFeatureSettings> mailFeatureSettings;
// Injected the list of mail feature settings
public HomeController(ILogger<HomeController> logger, IList<MailFeatureSettings> mailFeatureSettings)
{
_logger = logger;
this.mailFeatureSettings = mailFeatureSettings;
}
public IActionResult Index()
{
// Use the settings from mail feature settings list
ViewData["Email"] = mailFeatureSettings[0].From;
return View();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment