views:

244

answers:

4

How do you handle primitive types when using a IoC container?

I.e. given that you have:

class Pinger {
    private int timeout;
    private string targetMachine;

    public Pinger(int timeout, string targetMachine) {
        this.timeout = timeout;
        this.targetMachine = targetMachine;
    }

    public void CheckPing() {
        ...
    }
}

How would you obtain the int and string constructor arguments?

+1  A: 

Make another interface for this.

Then you will get something like:

public Pinger(IExtraConfiguration extraConfig)
{
   timeout = extraconfig.TimeOut;
   targetmachine = extraconfig.TargetMachine;
}

I don't know about other IOC containers, but Castle Windsor resolves these extra constructor parameters automatically.

Gerrie Schenck
+1  A: 

It depends. The IoC-Container StructureMap will allow you to declare those dependencies when you configure the instance at the beginning of your execution.

e.g. in a registry

ForRequestedType<Pinger>()
  .TheDefault.Is.OfConcreteType<Pinger>()
  .WithCtorArg("timeout").EqualTo(5000)
  .WithCtorArg("targetMachine").EqualToAppSetting("machine");
flq
+1  A: 

In Spring, one can look up property values from a property file using ${propertyName} notation

<bean class="blah.Pinger">
    <constructor-arg value="${blah.timeout}"/>
    <constructor-arg value="${blah.targetMachine}"/>
</bean>

In Spring.net the same functionality is provided by the PropertyPlaceholderConfigurer, which has the same syntax, and uses name value sections in config files.

Andy
+2  A: 

I'm not sure if your difficulty is the value types or the concrete type. Neither is a problem. You don't need to introduce a configuration interface (it's useful if you want to pass the same parameters to multiple objects, but not in the case you've given). Anyway, here's the Windsor fluent code, I'm sure someone will submit an XML version soon.

container.Register(
            Component.For(typeof(Pinger))
                .ImplementedBy(typeof(Pinger))  // This might not be necessary
                .Parameters(Parameter.ForKey("timeout").Eq("5000"),
                            Parameter.ForKey("targetMachine").Eq("machine")
                )
            );
Julian Birch