【问题标题】:Bind concrete object to IOptions interface in dotnetBind concrete object to IOptions interface in dotnet
【发布时间】:2022-12-02 03:54:25
【问题描述】:

I want to register an IOptions implementation having an object with needed data . Having a IConfiguration with such data I can easily do this like this: (assuming IConfiguration has everything inside)

.ConfigureServices((context, services) =>
{
    services.AddOptions<SmtpConfig>().BindConfiguration(nameof(SmtpConfig));
})  

No how can I do the same with concrete data in place? Something like this:

services.AddOptions<SmtpConfig>().Bind(myData);

or

services.AddOptions<SmtpConfig>().Bind(new SmtpConfig() { ... });

【问题讨论】:

    标签: c# .net-core dependency-injection configuration


    【解决方案1】:

    To register an IOptions implementation using a concrete object, you can use the Configure method of the IServiceCollection interface, like this:

    var myData = new SmtpConfig() { ... };
    services.Configure<SmtpConfig>(options => options = myData);
    

    This will register the SmtpConfig object as the implementation of the IOptions&lt;SmtpConfig&gt; interface, so that it can be injected into other classes via constructor injection.

    Alternatively, if you want to register the SmtpConfig object as a singleton, you can use the AddSingleton method of the IServiceCollection interface, like this:

    var myData = new SmtpConfig() { ... };
    services.AddSingleton<SmtpConfig>(myData);
    

    This will ensure that the same instance of the SmtpConfig object is used throughout the application.

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 2017-08-02
      • 2012-05-14
      • 1970-01-01
      • 2022-10-04
      • 2021-12-07
      • 2013-08-03
      • 2022-12-02
      • 2022-12-26
      相关资源
      最近更新 更多