Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitive types and IoC containers

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?

like image 559
Andreas Avatar asked Jan 29 '09 09:01

Andreas


2 Answers

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.

like image 100
Gerrie Schenck Avatar answered Sep 20 '22 15:09

Gerrie Schenck


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")
                )
            );
like image 40
Julian Birch Avatar answered Sep 18 '22 15:09

Julian Birch