services.Configure() or services.AddSingleton().Get()?











up vote
0
down vote

favorite












As known there are two ways to get option classes in ASP.NET Core 2:





  1. Using services.Configure<>() like this:



    services.AddOption();
    services.Configure<ApplicationOptions>(Configuration.GetSection("applicationSettings"));



  2. or using services.AddSingleton(Configuration.Get()) like this:



    services.AddSingleton(Configuration.GetSection("applicationSettings")
    .Get<ApplicationOptions>());



But what advantages or disadvantages do these different approaches have?










share|improve this question
























  • Read this and decide which you prefer simpleinjector.readthedocs.io/en/latest/…
    – Nkosi
    Nov 22 at 9:41















up vote
0
down vote

favorite












As known there are two ways to get option classes in ASP.NET Core 2:





  1. Using services.Configure<>() like this:



    services.AddOption();
    services.Configure<ApplicationOptions>(Configuration.GetSection("applicationSettings"));



  2. or using services.AddSingleton(Configuration.Get()) like this:



    services.AddSingleton(Configuration.GetSection("applicationSettings")
    .Get<ApplicationOptions>());



But what advantages or disadvantages do these different approaches have?










share|improve this question
























  • Read this and decide which you prefer simpleinjector.readthedocs.io/en/latest/…
    – Nkosi
    Nov 22 at 9:41













up vote
0
down vote

favorite









up vote
0
down vote

favorite











As known there are two ways to get option classes in ASP.NET Core 2:





  1. Using services.Configure<>() like this:



    services.AddOption();
    services.Configure<ApplicationOptions>(Configuration.GetSection("applicationSettings"));



  2. or using services.AddSingleton(Configuration.Get()) like this:



    services.AddSingleton(Configuration.GetSection("applicationSettings")
    .Get<ApplicationOptions>());



But what advantages or disadvantages do these different approaches have?










share|improve this question















As known there are two ways to get option classes in ASP.NET Core 2:





  1. Using services.Configure<>() like this:



    services.AddOption();
    services.Configure<ApplicationOptions>(Configuration.GetSection("applicationSettings"));



  2. or using services.AddSingleton(Configuration.Get()) like this:



    services.AddSingleton(Configuration.GetSection("applicationSettings")
    .Get<ApplicationOptions>());



But what advantages or disadvantages do these different approaches have?







c# asp.net-core configuration






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 13:13









poke

206k44325383




206k44325383










asked Nov 22 at 5:47









ShefardPT

42




42












  • Read this and decide which you prefer simpleinjector.readthedocs.io/en/latest/…
    – Nkosi
    Nov 22 at 9:41


















  • Read this and decide which you prefer simpleinjector.readthedocs.io/en/latest/…
    – Nkosi
    Nov 22 at 9:41
















Read this and decide which you prefer simpleinjector.readthedocs.io/en/latest/…
– Nkosi
Nov 22 at 9:41




Read this and decide which you prefer simpleinjector.readthedocs.io/en/latest/…
– Nkosi
Nov 22 at 9:41












2 Answers
2






active

oldest

votes

















up vote
0
down vote













Short answer : The 1st way adds an Options, and the 2nd way registers a plain singleton service.



I always prefer Options Pattern if possible.



Behind the scenes , the Configure<TOptions>() will invoke services.AddSingleton<>() to register a singleton service to configure options. However, To configure options, we should always use the 1st way. As the Configure<TOptions>(config) (and all kind of other configure<>() methods) will do all the heavy-lifting for us. :




  1. For example, if we would like to store two different instance for the same type, how can we do that with a plain singleton service ? In fact, that' exactly what named options does.


  2. Also, it hard to auto reload a plain singleton service according to a file change to applicationSettings.json.







share|improve this answer





















  • Thanks a lot for the quite comprehesive answer!
    – ShefardPT
    Nov 22 at 10:26


















up vote
0
down vote













Using Configure<ApplicationOptions> allows the options pattern. The options pattern is a nice way to configure things using various configuration sources. In your example, you are configuring the ApplicationOptions using a Microsoft.Extensions.Configuration source. But you can also configure it through other sources at the same time:



// configure using configuration
services.Configure<ApplicationOptions>(Configuration.GetSection("applicationSettings"));

// then apply a configuration function
services.Configure<ApplicationOptions>(options =>
{
// overwrite previous values
options.Foo = "bar";
});


There are a few other ways to adjust the configuration as well, for example using post-configures which allows you to easily compose things that utilize options but may need to establish certain defaults or fallbacks.



Option objects will be configured at the time they are used, so when you call services.Configure(), there is actually nothing being configured at that time. Instead, configurations are registered with the DI container. And then, when the options are resolved, all configurations for a certain type will be invoked (which allows for composition). This allows options to also support updating configuration; so when you update your appsettings.json at run-time, options are able to receive the updated values.



In order to consume options, you need to inject IOptions<ApplicationOptions> (or IOptionsSnapshot<ApplicationOptions> if you need updating options). This is a wrapper around the options object which will invoke the options pattern.





On the other hand, calling AddSingleton<ApplicationOptions> just registers a singleton instance as a fixed value. So what gets registered with the DI provider is whatever value Configuration.GetSection("applicationSettings").Get<ApplicationOptions>() returns at that exact moment.



This has the benefit that you do not need to use the options pattern; instead of having to inject IOptions<ApplicationOptions> into your types, you can just depend on ApplicationOptions directly. So you don’t take a dependency on the Options framework. This is good for independent libraries that want to be used in different scenarios where the options pattern might not be available by default.



However, since this registers a fixed instance, you are also limited to those exact values. You cannot have those values update later when the configuration source is changed, and also cannot use that one configuration source in combination with other configurations.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424593%2fservices-configure-or-services-addsingleton-get%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    Short answer : The 1st way adds an Options, and the 2nd way registers a plain singleton service.



    I always prefer Options Pattern if possible.



    Behind the scenes , the Configure<TOptions>() will invoke services.AddSingleton<>() to register a singleton service to configure options. However, To configure options, we should always use the 1st way. As the Configure<TOptions>(config) (and all kind of other configure<>() methods) will do all the heavy-lifting for us. :




    1. For example, if we would like to store two different instance for the same type, how can we do that with a plain singleton service ? In fact, that' exactly what named options does.


    2. Also, it hard to auto reload a plain singleton service according to a file change to applicationSettings.json.







    share|improve this answer





















    • Thanks a lot for the quite comprehesive answer!
      – ShefardPT
      Nov 22 at 10:26















    up vote
    0
    down vote













    Short answer : The 1st way adds an Options, and the 2nd way registers a plain singleton service.



    I always prefer Options Pattern if possible.



    Behind the scenes , the Configure<TOptions>() will invoke services.AddSingleton<>() to register a singleton service to configure options. However, To configure options, we should always use the 1st way. As the Configure<TOptions>(config) (and all kind of other configure<>() methods) will do all the heavy-lifting for us. :




    1. For example, if we would like to store two different instance for the same type, how can we do that with a plain singleton service ? In fact, that' exactly what named options does.


    2. Also, it hard to auto reload a plain singleton service according to a file change to applicationSettings.json.







    share|improve this answer





















    • Thanks a lot for the quite comprehesive answer!
      – ShefardPT
      Nov 22 at 10:26













    up vote
    0
    down vote










    up vote
    0
    down vote









    Short answer : The 1st way adds an Options, and the 2nd way registers a plain singleton service.



    I always prefer Options Pattern if possible.



    Behind the scenes , the Configure<TOptions>() will invoke services.AddSingleton<>() to register a singleton service to configure options. However, To configure options, we should always use the 1st way. As the Configure<TOptions>(config) (and all kind of other configure<>() methods) will do all the heavy-lifting for us. :




    1. For example, if we would like to store two different instance for the same type, how can we do that with a plain singleton service ? In fact, that' exactly what named options does.


    2. Also, it hard to auto reload a plain singleton service according to a file change to applicationSettings.json.







    share|improve this answer












    Short answer : The 1st way adds an Options, and the 2nd way registers a plain singleton service.



    I always prefer Options Pattern if possible.



    Behind the scenes , the Configure<TOptions>() will invoke services.AddSingleton<>() to register a singleton service to configure options. However, To configure options, we should always use the 1st way. As the Configure<TOptions>(config) (and all kind of other configure<>() methods) will do all the heavy-lifting for us. :




    1. For example, if we would like to store two different instance for the same type, how can we do that with a plain singleton service ? In fact, that' exactly what named options does.


    2. Also, it hard to auto reload a plain singleton service according to a file change to applicationSettings.json.








    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 22 at 9:56









    itminus

    2,6511320




    2,6511320












    • Thanks a lot for the quite comprehesive answer!
      – ShefardPT
      Nov 22 at 10:26


















    • Thanks a lot for the quite comprehesive answer!
      – ShefardPT
      Nov 22 at 10:26
















    Thanks a lot for the quite comprehesive answer!
    – ShefardPT
    Nov 22 at 10:26




    Thanks a lot for the quite comprehesive answer!
    – ShefardPT
    Nov 22 at 10:26












    up vote
    0
    down vote













    Using Configure<ApplicationOptions> allows the options pattern. The options pattern is a nice way to configure things using various configuration sources. In your example, you are configuring the ApplicationOptions using a Microsoft.Extensions.Configuration source. But you can also configure it through other sources at the same time:



    // configure using configuration
    services.Configure<ApplicationOptions>(Configuration.GetSection("applicationSettings"));

    // then apply a configuration function
    services.Configure<ApplicationOptions>(options =>
    {
    // overwrite previous values
    options.Foo = "bar";
    });


    There are a few other ways to adjust the configuration as well, for example using post-configures which allows you to easily compose things that utilize options but may need to establish certain defaults or fallbacks.



    Option objects will be configured at the time they are used, so when you call services.Configure(), there is actually nothing being configured at that time. Instead, configurations are registered with the DI container. And then, when the options are resolved, all configurations for a certain type will be invoked (which allows for composition). This allows options to also support updating configuration; so when you update your appsettings.json at run-time, options are able to receive the updated values.



    In order to consume options, you need to inject IOptions<ApplicationOptions> (or IOptionsSnapshot<ApplicationOptions> if you need updating options). This is a wrapper around the options object which will invoke the options pattern.





    On the other hand, calling AddSingleton<ApplicationOptions> just registers a singleton instance as a fixed value. So what gets registered with the DI provider is whatever value Configuration.GetSection("applicationSettings").Get<ApplicationOptions>() returns at that exact moment.



    This has the benefit that you do not need to use the options pattern; instead of having to inject IOptions<ApplicationOptions> into your types, you can just depend on ApplicationOptions directly. So you don’t take a dependency on the Options framework. This is good for independent libraries that want to be used in different scenarios where the options pattern might not be available by default.



    However, since this registers a fixed instance, you are also limited to those exact values. You cannot have those values update later when the configuration source is changed, and also cannot use that one configuration source in combination with other configurations.






    share|improve this answer

























      up vote
      0
      down vote













      Using Configure<ApplicationOptions> allows the options pattern. The options pattern is a nice way to configure things using various configuration sources. In your example, you are configuring the ApplicationOptions using a Microsoft.Extensions.Configuration source. But you can also configure it through other sources at the same time:



      // configure using configuration
      services.Configure<ApplicationOptions>(Configuration.GetSection("applicationSettings"));

      // then apply a configuration function
      services.Configure<ApplicationOptions>(options =>
      {
      // overwrite previous values
      options.Foo = "bar";
      });


      There are a few other ways to adjust the configuration as well, for example using post-configures which allows you to easily compose things that utilize options but may need to establish certain defaults or fallbacks.



      Option objects will be configured at the time they are used, so when you call services.Configure(), there is actually nothing being configured at that time. Instead, configurations are registered with the DI container. And then, when the options are resolved, all configurations for a certain type will be invoked (which allows for composition). This allows options to also support updating configuration; so when you update your appsettings.json at run-time, options are able to receive the updated values.



      In order to consume options, you need to inject IOptions<ApplicationOptions> (or IOptionsSnapshot<ApplicationOptions> if you need updating options). This is a wrapper around the options object which will invoke the options pattern.





      On the other hand, calling AddSingleton<ApplicationOptions> just registers a singleton instance as a fixed value. So what gets registered with the DI provider is whatever value Configuration.GetSection("applicationSettings").Get<ApplicationOptions>() returns at that exact moment.



      This has the benefit that you do not need to use the options pattern; instead of having to inject IOptions<ApplicationOptions> into your types, you can just depend on ApplicationOptions directly. So you don’t take a dependency on the Options framework. This is good for independent libraries that want to be used in different scenarios where the options pattern might not be available by default.



      However, since this registers a fixed instance, you are also limited to those exact values. You cannot have those values update later when the configuration source is changed, and also cannot use that one configuration source in combination with other configurations.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        Using Configure<ApplicationOptions> allows the options pattern. The options pattern is a nice way to configure things using various configuration sources. In your example, you are configuring the ApplicationOptions using a Microsoft.Extensions.Configuration source. But you can also configure it through other sources at the same time:



        // configure using configuration
        services.Configure<ApplicationOptions>(Configuration.GetSection("applicationSettings"));

        // then apply a configuration function
        services.Configure<ApplicationOptions>(options =>
        {
        // overwrite previous values
        options.Foo = "bar";
        });


        There are a few other ways to adjust the configuration as well, for example using post-configures which allows you to easily compose things that utilize options but may need to establish certain defaults or fallbacks.



        Option objects will be configured at the time they are used, so when you call services.Configure(), there is actually nothing being configured at that time. Instead, configurations are registered with the DI container. And then, when the options are resolved, all configurations for a certain type will be invoked (which allows for composition). This allows options to also support updating configuration; so when you update your appsettings.json at run-time, options are able to receive the updated values.



        In order to consume options, you need to inject IOptions<ApplicationOptions> (or IOptionsSnapshot<ApplicationOptions> if you need updating options). This is a wrapper around the options object which will invoke the options pattern.





        On the other hand, calling AddSingleton<ApplicationOptions> just registers a singleton instance as a fixed value. So what gets registered with the DI provider is whatever value Configuration.GetSection("applicationSettings").Get<ApplicationOptions>() returns at that exact moment.



        This has the benefit that you do not need to use the options pattern; instead of having to inject IOptions<ApplicationOptions> into your types, you can just depend on ApplicationOptions directly. So you don’t take a dependency on the Options framework. This is good for independent libraries that want to be used in different scenarios where the options pattern might not be available by default.



        However, since this registers a fixed instance, you are also limited to those exact values. You cannot have those values update later when the configuration source is changed, and also cannot use that one configuration source in combination with other configurations.






        share|improve this answer












        Using Configure<ApplicationOptions> allows the options pattern. The options pattern is a nice way to configure things using various configuration sources. In your example, you are configuring the ApplicationOptions using a Microsoft.Extensions.Configuration source. But you can also configure it through other sources at the same time:



        // configure using configuration
        services.Configure<ApplicationOptions>(Configuration.GetSection("applicationSettings"));

        // then apply a configuration function
        services.Configure<ApplicationOptions>(options =>
        {
        // overwrite previous values
        options.Foo = "bar";
        });


        There are a few other ways to adjust the configuration as well, for example using post-configures which allows you to easily compose things that utilize options but may need to establish certain defaults or fallbacks.



        Option objects will be configured at the time they are used, so when you call services.Configure(), there is actually nothing being configured at that time. Instead, configurations are registered with the DI container. And then, when the options are resolved, all configurations for a certain type will be invoked (which allows for composition). This allows options to also support updating configuration; so when you update your appsettings.json at run-time, options are able to receive the updated values.



        In order to consume options, you need to inject IOptions<ApplicationOptions> (or IOptionsSnapshot<ApplicationOptions> if you need updating options). This is a wrapper around the options object which will invoke the options pattern.





        On the other hand, calling AddSingleton<ApplicationOptions> just registers a singleton instance as a fixed value. So what gets registered with the DI provider is whatever value Configuration.GetSection("applicationSettings").Get<ApplicationOptions>() returns at that exact moment.



        This has the benefit that you do not need to use the options pattern; instead of having to inject IOptions<ApplicationOptions> into your types, you can just depend on ApplicationOptions directly. So you don’t take a dependency on the Options framework. This is good for independent libraries that want to be used in different scenarios where the options pattern might not be available by default.



        However, since this registers a fixed instance, you are also limited to those exact values. You cannot have those values update later when the configuration source is changed, and also cannot use that one configuration source in combination with other configurations.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 at 13:11









        poke

        206k44325383




        206k44325383






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424593%2fservices-configure-or-services-addsingleton-get%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks