Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring.Net ref to Dictionary item

I can't find out how use an item defined in dictionary (xml spring config) at other place in the spring xml file. I tried something like this, but I ever get an error in init of "obj1".

  <object name="Paths" id="Paths" type="System.Collections.Generic.Dictionary&lt;string,string&gt;">
    <constructor-arg>
      <dictionary key-type="string" value-type="string">
        <entry key="cfgFile">
          <value>config.txt</value>
        </entry>
      </dictionary>
    </constructor-arg>
  </object>  
  <object name="obj1" type="MyTestClass" depends-on="Paths">
    <property name="cfg" expression="${Paths['cfgFile']}"/>
  </object>

Thanks for your help...

like image 792
Perun_x Avatar asked Sep 17 '26 02:09

Perun_x


1 Answers

My original answer was accepted, but now I believe a better answer would be:

Your expression is not correct, it should be:

<object name="obj1" type="MyTestClass" depends-on="Paths">
  <property name="cfg" expression="@(Paths)['cfgFile']"/>
</object>

You can use the @(object-id-here) expression syntax to retrieve an object from the Spring context using an expression.

Edit - below is the answer that was accepted

I can imagine that you would like this kind of configuration to be available in your app.config. If so, you can use the PropertyPlaceholderConfigurer; see the example in section 5.9.2.1.

In your case, it would look something like this:

<!-- app.config -->
<configuration>

  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
    </sectionGroup>
    <section name="PathConfiguration" type="System.Configuration.NameValueSectionHandler"/>
  </configSections>

  <PathConfiguration>
    <add key="cfgFile" value="config.txt"/>
    <add key="otherCfgFile" value="otherconfig.txt"/>
  </PathConfiguration>

  <spring>
    <context>
      <resource uri="mycongfig.xml"/>
    </context>
  </spring>

</configuration>

And your myconfig.xml contains:

<!-- ... -->
<object name="obj1" type="MyTestClass">
    <property name="cfg" value="${cfgFile}"/>
</object>

<object name="appConfigPropertyHolder" 
        type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core">

    <property name="configSections">          
      <value>PathConfiguration</value>                              
    </property>              

</object>
<!-- ... -->

Note that instead of app.config, you can use any other IResource.

An alternative solution is to define the cfgFile as an object in your configuration and then in your dictionary reference this object using value-ref (see spring docs 5.3.2.4 on how to do this). But this (probably) isn't what you are looking for, since you're injecting primitive values (so it's not worth the effort of creating an explicit ConfigurationObject).

like image 175
Marijn Avatar answered Sep 18 '26 15:09

Marijn