IOptions Injection

前端 未结 5 1750
情书的邮戳
情书的邮戳 2020-12-08 19:17

It seems to me that it\'s a bad idea to have a domain service require an instance of IOptions to pass it configuration. Now I\'ve got pull additional (unnecessary?) depend

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 20:21

    Technically nothing prevents you from registering your POCO classes with ASP.NET Core's Dependency Injection or create a wrapper class and return the IOption.Value from it.

    But you will lose the advanced features of the Options package, namely to get them updated automatically when the source changes as you can see in the source here.

    As you can see in that code example, if you register your options via services.Configure(Configuration.GetSection("AppSettings")); it will read and bind the settings from appsettings.json into the model and additionally track it for changes. When appsettings.json is edited, and will rebind the model with the new values as seen here.

    Of course you need to decide for yourself, if you want to leak a bit of infrastructure into your domain or pass on the extra features offered by the Microsoft.Extension.Options package. It's a pretty small package which is not tied to ASP.NET Core, so it can be used independent of it.

    The Microsoft.Extension.Options package is small enough that it only contains abstractions and the concrete services.Configure overload which for IConfiguration (which is closer tied to how the configuration is obtained, command line, json, environment, azure key vault, etc.) is a separate package.

    So all in all, its dependencies on "infrastructure" is pretty limited.

提交回复
热议问题