Monday, July 24, 2017

Dynamic Configuration Settings in ASP.NET Core

I read the great article about the configuration of ASP.NET Core web application - Strongly Typed Configuration Settings in ASP.NET Core. As for me, it is better than access via dictionary's keys but it is always boring to create another POCO classes. I prefer to use a dynamic object. And it is easy to replace POCO class with dynamic.

First of all, I replaced ConfigureServices method with the next code:

public void ConfigureServices(IServiceCollection services)
        services.AddOptions(); //be careful. don't miss options injection
        services.Configure< ExpandoObject >(Configuration.GetSection("MySettings"));

And inject settings in the controller:

private dynamic MySettings { get; set; }

public HomeController(IOptions< ExpandoObject > settings)

         MySettings = settings.Value;

Now, you could use it like usual instance.

public IActionResult Index()
         ViewBag.ApplicationName = MySettings.ApplicationName;
         return View();

This way has a number of disadvantages:
  • The risk of a typo - do you know how to detect if a property exists on an ExpandoObject? ExpandoObject is inherited from Dictionary. So check doesn't look graceful.
  • Complex properties. As I mentioned, ExpandoObject is inherited from Dictionary so we can't parse complex settings. We could create POCO class that has as a property another POCO class and fit our complex settings without any problem. But in the instance of ExpandoObject, we can't fit object to dynamic object what is represented in the settings.
Also, you could get more information about core configuration in Configuration in ASP.NET Core article.

No comments: