Create a named string in xml configuration

99 views Asked by At

It is possible to create a named registration for an interface or non-primitive, e.g.

...
<register type="ILogger" mapTo="PageAdminLogger" name="emergency" /> 
...

Is it also possible to create a named registration for a string, especially one that will be used multiple times? What I am aiming to do:

...
<container>
  <register type='System.String' name='serverAddress'>
    127.0.0.1
  </register>

  <register type='IFooConnector' mapTo='FooConnector'>
    <constructor>
      <param name='addr' dependencyName='serverAddress'/>
    </constructor>
  </register>

  <register type='IBarDoer' mapTo='BarDoerOnAServer'>
    <constructor>
      <param name='server' dependencyName='serverAddress'/>
    </constructor>
  </register>
</container>
...

So that when the FooConnector and the BarDoerOnAServer and constructed they both get "127.0.0.1" as the input to their constructors, but "127.0.0.1" is only coded in one place (reducing duplication), and also all the literal variables (e.g. ports, timeouts, usernames, ...) are configured in one place rather than being littered around the configuration file.

1

There are 1 answers

0
Randy Levy On BEST ANSWER

Yes you can create a named string using Unity's XML configuration.

To do this you would use the instance element.

In your example it would look like:

<container>
  <instance name='serverAddress' value='127.0.0.1' />

  <register type='IFooConnector' mapTo='FooConnector'>
    <constructor>
      <param name='addr' dependencyName='serverAddress'/>
    </constructor>
  </register>

  <register type='IBarDoer' mapTo='BarDoerOnAServer'>
    <constructor>
      <param name='server' dependencyName='serverAddress'/>
    </constructor>
  </register>
</container>