Accessing ConfigurationManager.AppSettings value from Spring.NET xml configuration
Asked Answered
R

2

6

I have a requirement that requires me to use Spring.net to get a connectionstring that is stored inside the app.config, and then inject the retrieved connectionstring to a instantiated object.

How can I do this using Spring.net's xml configuration?

For e.g., instead of my codes doing this:

// Spring.net config:
<object name="myService" type="com.acme.MyService, com.acme">
    <constructor-arg type="System.String" value="myConnectionName"/>
</object>

// Web.config:
<connectionStrings>
    <add name="myConnectionName" connectionString="DB_connectionstring"/>
</connectionStrings>
// Codes:
public class MyService {
    public MyService(string connectionName) {
        var connectionString = ConfigurationManager.AppSettings[connectionName];
        // use connectionString to create a DB connection, etc
    }
}

I want it like this:

 // Spring.net config:
<object name="myService" type="com.acme.MyService, com.acme">
    <constructor-arg type="System.String" ref="retrievedConnectionString"/>
</object>    
// How to make a call similar to "ConfigurationManager.AppSettings[connectionName]" and get the connection string from Web.config and put inside "retrievedConnectionString"?

// Web.config:
<connectionStrings>
    <add name="myConnectionName" connectionString="DB_connectionstring"/>
</connectionStrings>
// Codes:
public class MyService {
    public MyService(string connectionString) {
        // use connectionString to create a DB connection, etc
    }
}

Is it even possible to call ConfigurationManager.AppSettings[..] from Spring.net xml config?

Rowan answered 3/11, 2011 at 7:3 Comment(0)
K
7

In the past I used an expression to achieve this, but through this question and bbaia's answer, I found out that a better way to do this is using a VariablePlaceholderConfigurer. When you use a VariablePlaceholderConfigurer instead of my "expression-hack", you don't tie yourself to the appSettings / connectionStrings style configuration of your variables: you can switch to one of the VariableSources provided by spring.net or even implement your own IVariableSource.

Out-of-the-box, Spring.NET provides VariablePlaceholderConfigurers to retrieve variables from standard .NET settings like AppSettings, ConnectionStrings, UserSettings and ApplicationSettings. This is partially illustrated by bbaia's answer and you'll find a complete example below.

"Expression hack": calling ConfigurationManager from xml config

So, I don't advice you to use this, but this is the hack I used in the past, applied to your configuration:

<object object name="myService" type="com.acme.MyService, com.acme">
  <constructor-arg name="Connection" 
                   expression="T(System.Configuration.ConfigurationManager).ConnectionStrings['myConnectionName']" />
</object>

You can use this same approach for ConfigurationManager.AppSettings, e.g.:

<object object name="myService" type="com.acme.MyService, com.acme">
  <constructor-arg name="AnotherConstructorArgument" 
                   expression="T(System.Configuration.ConfigurationManager).AppSettings['mySetting']" />
</object>

VariablePlaceholderConfigurer: reference .NET settings from Spring.NET xml config

You can easily configure a VariablePlaceholderConfigurer to retrieve variables from standard .NET settings like AppSettings, ConnectionStrings, UserSettings and ApplicationSettings. For instance, consider this xml configuration:

<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net" >

  <object type="Spring.Objects.Factory.Config.VariablePlaceholderConfigurer, Spring.Core">
    <property name="VariableSources">
      <list>
        <object type="Spring.Objects.Factory.Config.ConnectionStringsVariableSource, Spring.Core" />
        <object type="Spring.Objects.Factory.Config.ConfigSectionVariableSource, Spring.Core">
          <!-- Sections to read, sepearated by comma (leave out spaces) -->
          <property name="SectionNames"
                    value="appSettings,applicationSettings/q7991262.Properties.Settings,userSettings/q7991262.Properties.Settings" />
        </object>
      </list>
    </property>
  </object>

  <!-- Note that you have to append '.connectionstring' to the key! -->
  <object id="usingConnectionStringsVariableSource" 
          type="q7991262.MyService, q7991262">
    <property name="Connection" 
              value="${myConnectionName.connectionString}" />
  </object>

  <object id="configSectionVariableSource" 
          type="q7991262.MyService, q7991262">
    <property name="Connection" 
              value="${myConnectionNameAppSettings}" />
  </object>

  <object id="userSettingsSection" 
          type="q7991262.MyService, q7991262">
    <property name="Connection" 
              value="${myConectionNameUserSetting}" />
  </object>

  <object id="applicationSetting" 
          type="q7991262.MyService, q7991262">
    <property name="Connection" 
              value="${myConectionNameApplicationSetting}" />
  </object>

</objects>

It reads the settings from this app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="q7991262.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
    </sectionGroup>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="q7991262.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <connectionStrings>
    <add name="myConnectionName" 
         connectionString="From connection string section."/>
  </connectionStrings>

  <appSettings>
    <add key="myConnectionNameAppSettings" 
         value="From app setting section." />
  </appSettings>

  <userSettings>
    <q7991262.Properties.Settings>
      <setting name="myConectionNameUserSetting" serializeAs="String">
        <value>My connection from user settings.</value>
      </setting>
    </q7991262.Properties.Settings>
  </userSettings>

  <applicationSettings>
    <q7991262.Properties.Settings>
      <setting name="myConectionNameApplicationSetting" serializeAs="String">
        <value>My connection from application settings.</value>
      </setting>
    </q7991262.Properties.Settings>
  </applicationSettings>

</configuration>

These configurations are taken from this working sample at github.

Kakapo answered 3/11, 2011 at 11:24 Comment(2)
ref: github.com/serra/stackoverflow/blob/master/spring-questions/…Kakapo
I mark this as the answer because it gave the examples to retrieve values from both appSettings and connectionStrings, which is what I exactly want.Rowan
C
3

Another solution is to use the VariablePlaceholderConfigurer : http://www.springframework.net/doc-latest/reference/html/objects.html#objects-variablesource

The ConnectionStringsVariableSource implementation allows you to get the value from the ConnectionString section in your config file.

<object type="Spring.Objects.Factory.Config.VariablePlaceholderConfigurer, Spring.Core">
  <property name="VariableSources">
    <list>
      <object type="Spring.Objects.Factory.Config.ConnectionStringsVariableSource, Spring.Core"/>
    </list>
  </property>
</object>

<object name="myService" type="com.acme.MyService, com.acme">
    <constructor-arg type="System.String" value="${myConnectionName.connectionString}"/>
</object>

Example from the Spring.NET forum: http://forum.springframework.net/showthread.php?3961

Contraception answered 3/11, 2011 at 12:43 Comment(2)
Was just about to add this one too, but it didn't work in my case because I forgot to add .connectionString to the name, which is required by the ConnectionStringsVariableSource. You can get the provider name using value="${myConnectionName.providerName}".Kakapo
Unfortunately, IVariableSource implementations are not documented. You have to dig into the code like you did.Contraception

© 2022 - 2024 — McMap. All rights reserved.