1

All I want to do is (in an app.config) define a singleton 'Int32'. The idea is that it will be a named registration, and used as a parameter in multiple other type definitions - meaning the actual int value itself only needs to be defined once (and reducing manual error).

Something along the lines of the following...

  <register type="int" name="MyInt">
    <lifetime type="singleton" />
    <constructor>
      <param name="value" value="23"/>          
    </constructor>
  </register>

Now I realise the Int32 structure doesn't have such a constructor, but what I am requesting seems so simple that I cant believe it cant be done.

Am I missing something obvious?

Cheers!

J_Williams
  • 53
  • 1
  • 4

2 Answers2

1

You should be able to specify a single instance:

<container>
  <instance name="FooBar" type="System.Int32" value="123" />
</container>

Which is resolved like so:

int value = container.Resolve<int>("FooBar");

If you would require to construct another type from configuration, it would be like so:

<!-- "SomeType" is a type here, but you can have any mapping here -->
<register type="SomeType">
  <constructor>
    <!-- "value" is the name of the constructor argument -->
    <param name="value" dependencyName="FooBar" />
  </constructor>
</register>
Caramiriel
  • 7,029
  • 3
  • 30
  • 50
0

Can you change behavior from Dependency injection to reading config file? Here good example how you can put int value to config file and read it without DI.

Second solution: you can wrap your int value into simple object with singl property and necessary constructor.

Anton Gorbunov
  • 1,414
  • 3
  • 16
  • 24
  • First option is out as trying to keep it all DI. I already have the latter suggestion implemented (small wrapper object), but it seems a bit clunky - hence this question! – J_Williams Nov 20 '17 at 10:19
  • May you use first solution? It allow change value from from app.config and use it value wherever in your code. – Anton Gorbunov Nov 20 '17 at 10:23
  • There is strong typed configuration, but this solution need some code. Here you can find description how you can made it: https://msdn.microsoft.com/en-us/library/2tw134k3.aspx – Anton Gorbunov Nov 20 '17 at 10:25