I’m trying to learn (remember I’m a newbie) the most effective ways to handle parameters in Ninject 2.0. This wasn’t a result of refactoring an actual project, I was just curious. I started out trying to bind a primitive type in a constructor.
Parameters and AttributesLet’s start by just binding a primitive type parameter. You can see below that the WorkoutRoom class takes a string in the constructor.
You’ll notice that I created a custom attribute RoomAttribute and then used that attribute on the constructor’s parameter. Now I can leverage the contextual binding syntax we covered last time.
Where ROOM_NAME is just a const string I’ve defined with the default name I want this to have. Now whenever Ninject needs a WorkoutRoom it will get one with the default room name.
The ConstructorArgumentIf you don’t mind coupling the injection wiring to the actual names of parameters you can use ConstructorArguments. Given the previous example I can rely on the fact that the parameter is named “roomName” and get rid of the attributes and use the following:
Interestingly, you can combine these two techniques. Leave the attribute on the parameter and make the default name something politely informative:
Now when your unit test runs and you check the room name
The assertion will tell you everything you need to know about what happened.
You can easily pass more than one constructor argument. Given the following constructor
You can test it with
You aren’t limited to primitive types with these techniques. Here’s an example taken from Ninject’s unit tests.
Where the barracks class has a constructor that looks like
You can use a ConstructorArgument like
Previous Related Posts