NetCore 2.2 Change SQLConnection using environment variable The Next CEO of Stack OverflowMySQL: @variable vs. variable. What's the difference?Get SqlConnection from DbConnectionC# SqlConnection ConnectionStringrails application controller method is undefined in childrenEntity Framework - Use Dynamic connection string with Oracle ProviderHow to communicate domain-specific errors from API to be parsed by client codeSignalR + SQLNotifications in .NetCoreMultiple connection to DbContext in EFCore and .net Core2.0Polly Circuit Breaker policy and HttpClient with ASP.NET Core APIADAL vs MSAL for .netcore api

Bartok - Syncopation (1): Meaning of notes in between Grand Staff

Is it ever safe to open a suspicious HTML file (e.g. email attachment)?

How to invert MapIndexed on a ragged structure? How to construct a tree from rules?

How many extra stops do monopods offer for tele photographs?

Won the lottery - how do I keep the money?

TikZ: How to reverse arrow direction without switching start/end point?

Is it convenient to ask the journal's editor for two additional days to complete a review?

Flying from Cape Town to England and return to another province

INSERT to a table from a database to other (same SQL Server) using Dynamic SQL

What steps are necessary to read a Modern SSD in Medieval Europe?

Unclear about dynamic binding

Domestic-to-international connection at Orlando (MCO)

Which one is the true statement?

Rotate a column

Where do students learn to solve polynomial equations these days?

Is it okay to majorly distort historical facts while writing a fiction story?

Writing differences on a blackboard

Math-accent symbol over parentheses enclosing accented symbol (amsmath)

Find non-case sensitive string in a mixed list of elements?

Does increasing your ability score affect your main stat?

Why the difference in type-inference over the as-pattern in two similar function definitions?

Axiom Schema vs Axiom

Necessary condition on homology group for a set to be contractible

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?



NetCore 2.2 Change SQLConnection using environment variable



The Next CEO of Stack OverflowMySQL: @variable vs. variable. What's the difference?Get SqlConnection from DbConnectionC# SqlConnection ConnectionStringrails application controller method is undefined in childrenEntity Framework - Use Dynamic connection string with Oracle ProviderHow to communicate domain-specific errors from API to be parsed by client codeSignalR + SQLNotifications in .NetCoreMultiple connection to DbContext in EFCore and .net Core2.0Polly Circuit Breaker policy and HttpClient with ASP.NET Core APIADAL vs MSAL for .netcore api










0















Need assistance with dynamically changing the connectionstring supplied in an API for netcore 2.2.



This is my sample code



Public StartUp



_connectionString = cryptography.GetProtectedValue("RandomName", dbEnvironmentVariableName);



Public ConfigureServices



services.AddDbContextPool(s => s.UseSqlServer(_connectionString));



The user can change the Environment Variable at anytime and I need to have the API pick up this change dynamically each time it is changed.



I can't find anywhere to see that this is occurring except setting up something in the controller, but that just seems wrong.



Any thoughts.










share|improve this question


























    0















    Need assistance with dynamically changing the connectionstring supplied in an API for netcore 2.2.



    This is my sample code



    Public StartUp



    _connectionString = cryptography.GetProtectedValue("RandomName", dbEnvironmentVariableName);



    Public ConfigureServices



    services.AddDbContextPool(s => s.UseSqlServer(_connectionString));



    The user can change the Environment Variable at anytime and I need to have the API pick up this change dynamically each time it is changed.



    I can't find anywhere to see that this is occurring except setting up something in the controller, but that just seems wrong.



    Any thoughts.










    share|improve this question
























      0












      0








      0








      Need assistance with dynamically changing the connectionstring supplied in an API for netcore 2.2.



      This is my sample code



      Public StartUp



      _connectionString = cryptography.GetProtectedValue("RandomName", dbEnvironmentVariableName);



      Public ConfigureServices



      services.AddDbContextPool(s => s.UseSqlServer(_connectionString));



      The user can change the Environment Variable at anytime and I need to have the API pick up this change dynamically each time it is changed.



      I can't find anywhere to see that this is occurring except setting up something in the controller, but that just seems wrong.



      Any thoughts.










      share|improve this question














      Need assistance with dynamically changing the connectionstring supplied in an API for netcore 2.2.



      This is my sample code



      Public StartUp



      _connectionString = cryptography.GetProtectedValue("RandomName", dbEnvironmentVariableName);



      Public ConfigureServices



      services.AddDbContextPool(s => s.UseSqlServer(_connectionString));



      The user can change the Environment Variable at anytime and I need to have the API pick up this change dynamically each time it is changed.



      I can't find anywhere to see that this is occurring except setting up something in the controller, but that just seems wrong.



      Any thoughts.







      sql controller connection-string asp.net-core-webapi






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 16:13









      qwerty1906qwerty1906

      254




      254






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Well, first, you need to stop using connection pooling. This allows multiple instances of your context to use the same connection, which is not something you want if that connection needs to change on the fly.



          Then, you need to get the connection string inside the DbContext registration, so that each time an instance is created, it gets the connection string anew. As you have it now, it's global.



          services.AddDbContext<MyContext>((provider, options) =>

          // get connection string
          options.UseSqlServer(connectionString);
          );


          I'm not sure how to write this code for you as it's not clear what's going on with cryptography.GetProtectedValue("RandomName", dbEnvironmentVariableName). In general, here, provider is going to be an instance of IServiceProvider, and you want to use that to get the various services you need to make this call happen.






          share|improve this answer























          • Cryptography just returns an unencrypted connection string. Ok on the connection pool, that makes sense. On the other part, I don't think this still accomplishes changing the connection while the API is up and running. When a new instance is created then I agree, but when the API is already started it would not reset the connectionstring using this method. Hope that makes sense.

            – qwerty1906
            Mar 8 at 20:16






          • 1





            The context is request-scoped, so each request will get it's own instance, with the current connection string at that time. You are correct that once the instance is created, the connection string value is locked, and that is the case regardless. Config reload itself only happens on a per-request basis, so that's not actually an issue in practice. However, if you intend to change the connection string mid-request, then you are in fact out of luck.

            – Chris Pratt
            Mar 11 at 12:42












          • Thanks, that is what I was figuring, just wanted to make sure.

            – qwerty1906
            Mar 11 at 21:56











          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',
          autoActivateHeartbeat: false,
          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%2f55066993%2fnetcore-2-2-change-sqlconnection-using-environment-variable%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Well, first, you need to stop using connection pooling. This allows multiple instances of your context to use the same connection, which is not something you want if that connection needs to change on the fly.



          Then, you need to get the connection string inside the DbContext registration, so that each time an instance is created, it gets the connection string anew. As you have it now, it's global.



          services.AddDbContext<MyContext>((provider, options) =>

          // get connection string
          options.UseSqlServer(connectionString);
          );


          I'm not sure how to write this code for you as it's not clear what's going on with cryptography.GetProtectedValue("RandomName", dbEnvironmentVariableName). In general, here, provider is going to be an instance of IServiceProvider, and you want to use that to get the various services you need to make this call happen.






          share|improve this answer























          • Cryptography just returns an unencrypted connection string. Ok on the connection pool, that makes sense. On the other part, I don't think this still accomplishes changing the connection while the API is up and running. When a new instance is created then I agree, but when the API is already started it would not reset the connectionstring using this method. Hope that makes sense.

            – qwerty1906
            Mar 8 at 20:16






          • 1





            The context is request-scoped, so each request will get it's own instance, with the current connection string at that time. You are correct that once the instance is created, the connection string value is locked, and that is the case regardless. Config reload itself only happens on a per-request basis, so that's not actually an issue in practice. However, if you intend to change the connection string mid-request, then you are in fact out of luck.

            – Chris Pratt
            Mar 11 at 12:42












          • Thanks, that is what I was figuring, just wanted to make sure.

            – qwerty1906
            Mar 11 at 21:56















          1














          Well, first, you need to stop using connection pooling. This allows multiple instances of your context to use the same connection, which is not something you want if that connection needs to change on the fly.



          Then, you need to get the connection string inside the DbContext registration, so that each time an instance is created, it gets the connection string anew. As you have it now, it's global.



          services.AddDbContext<MyContext>((provider, options) =>

          // get connection string
          options.UseSqlServer(connectionString);
          );


          I'm not sure how to write this code for you as it's not clear what's going on with cryptography.GetProtectedValue("RandomName", dbEnvironmentVariableName). In general, here, provider is going to be an instance of IServiceProvider, and you want to use that to get the various services you need to make this call happen.






          share|improve this answer























          • Cryptography just returns an unencrypted connection string. Ok on the connection pool, that makes sense. On the other part, I don't think this still accomplishes changing the connection while the API is up and running. When a new instance is created then I agree, but when the API is already started it would not reset the connectionstring using this method. Hope that makes sense.

            – qwerty1906
            Mar 8 at 20:16






          • 1





            The context is request-scoped, so each request will get it's own instance, with the current connection string at that time. You are correct that once the instance is created, the connection string value is locked, and that is the case regardless. Config reload itself only happens on a per-request basis, so that's not actually an issue in practice. However, if you intend to change the connection string mid-request, then you are in fact out of luck.

            – Chris Pratt
            Mar 11 at 12:42












          • Thanks, that is what I was figuring, just wanted to make sure.

            – qwerty1906
            Mar 11 at 21:56













          1












          1








          1







          Well, first, you need to stop using connection pooling. This allows multiple instances of your context to use the same connection, which is not something you want if that connection needs to change on the fly.



          Then, you need to get the connection string inside the DbContext registration, so that each time an instance is created, it gets the connection string anew. As you have it now, it's global.



          services.AddDbContext<MyContext>((provider, options) =>

          // get connection string
          options.UseSqlServer(connectionString);
          );


          I'm not sure how to write this code for you as it's not clear what's going on with cryptography.GetProtectedValue("RandomName", dbEnvironmentVariableName). In general, here, provider is going to be an instance of IServiceProvider, and you want to use that to get the various services you need to make this call happen.






          share|improve this answer













          Well, first, you need to stop using connection pooling. This allows multiple instances of your context to use the same connection, which is not something you want if that connection needs to change on the fly.



          Then, you need to get the connection string inside the DbContext registration, so that each time an instance is created, it gets the connection string anew. As you have it now, it's global.



          services.AddDbContext<MyContext>((provider, options) =>

          // get connection string
          options.UseSqlServer(connectionString);
          );


          I'm not sure how to write this code for you as it's not clear what's going on with cryptography.GetProtectedValue("RandomName", dbEnvironmentVariableName). In general, here, provider is going to be an instance of IServiceProvider, and you want to use that to get the various services you need to make this call happen.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 8 at 16:34









          Chris PrattChris Pratt

          160k21243310




          160k21243310












          • Cryptography just returns an unencrypted connection string. Ok on the connection pool, that makes sense. On the other part, I don't think this still accomplishes changing the connection while the API is up and running. When a new instance is created then I agree, but when the API is already started it would not reset the connectionstring using this method. Hope that makes sense.

            – qwerty1906
            Mar 8 at 20:16






          • 1





            The context is request-scoped, so each request will get it's own instance, with the current connection string at that time. You are correct that once the instance is created, the connection string value is locked, and that is the case regardless. Config reload itself only happens on a per-request basis, so that's not actually an issue in practice. However, if you intend to change the connection string mid-request, then you are in fact out of luck.

            – Chris Pratt
            Mar 11 at 12:42












          • Thanks, that is what I was figuring, just wanted to make sure.

            – qwerty1906
            Mar 11 at 21:56

















          • Cryptography just returns an unencrypted connection string. Ok on the connection pool, that makes sense. On the other part, I don't think this still accomplishes changing the connection while the API is up and running. When a new instance is created then I agree, but when the API is already started it would not reset the connectionstring using this method. Hope that makes sense.

            – qwerty1906
            Mar 8 at 20:16






          • 1





            The context is request-scoped, so each request will get it's own instance, with the current connection string at that time. You are correct that once the instance is created, the connection string value is locked, and that is the case regardless. Config reload itself only happens on a per-request basis, so that's not actually an issue in practice. However, if you intend to change the connection string mid-request, then you are in fact out of luck.

            – Chris Pratt
            Mar 11 at 12:42












          • Thanks, that is what I was figuring, just wanted to make sure.

            – qwerty1906
            Mar 11 at 21:56
















          Cryptography just returns an unencrypted connection string. Ok on the connection pool, that makes sense. On the other part, I don't think this still accomplishes changing the connection while the API is up and running. When a new instance is created then I agree, but when the API is already started it would not reset the connectionstring using this method. Hope that makes sense.

          – qwerty1906
          Mar 8 at 20:16





          Cryptography just returns an unencrypted connection string. Ok on the connection pool, that makes sense. On the other part, I don't think this still accomplishes changing the connection while the API is up and running. When a new instance is created then I agree, but when the API is already started it would not reset the connectionstring using this method. Hope that makes sense.

          – qwerty1906
          Mar 8 at 20:16




          1




          1





          The context is request-scoped, so each request will get it's own instance, with the current connection string at that time. You are correct that once the instance is created, the connection string value is locked, and that is the case regardless. Config reload itself only happens on a per-request basis, so that's not actually an issue in practice. However, if you intend to change the connection string mid-request, then you are in fact out of luck.

          – Chris Pratt
          Mar 11 at 12:42






          The context is request-scoped, so each request will get it's own instance, with the current connection string at that time. You are correct that once the instance is created, the connection string value is locked, and that is the case regardless. Config reload itself only happens on a per-request basis, so that's not actually an issue in practice. However, if you intend to change the connection string mid-request, then you are in fact out of luck.

          – Chris Pratt
          Mar 11 at 12:42














          Thanks, that is what I was figuring, just wanted to make sure.

          – qwerty1906
          Mar 11 at 21:56





          Thanks, that is what I was figuring, just wanted to make sure.

          – qwerty1906
          Mar 11 at 21:56



















          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.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55066993%2fnetcore-2-2-change-sqlconnection-using-environment-variable%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

          Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

          Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

          2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived