Following on from my previous posting on how to implement the IContainer in structure map, I have hit what I hope is my last problem for a while.
How does one pass additional (non Structuremap injected) objects into a constructor?
Lets take the following from a sample console application I have for testing this stuff out.
static void Main(string[] args)
{
_container = StructureMapConfig.GetContainer();
_userService = _container.GetInstance<IUserService>();
}
This throws the following error because my constructor has the randomParam and structuremap has no idea how to fill the gap:
An unhandled exception of type 'StructureMap.StructureMapBuildPlanException' occurred in StructureMap.dll
Additional information: Unable to create a build plan for concrete type CommonServices.UserService
Constructor:
public UserService(IUserRepository userRepository, IStringService stringService, string randomParam)
{
_userRepository = userRepository;
_stringService = stringService;
}
In my registry I define my user service like so:
this.For<IUserService>().Use<UserService>();
The question I have is how do I do this in the simplest way?
I found this link but can not see how to use the suggestions as I would have to make my calling class aware of the dependencies of the UserService. AS you can see some of those are Data layer items, and I do not want to tell my UI layer about them.
http://structuremap.github.io/resolving/passing-arguments-at-runtime/
You should be able to target your parameter like so:
this.For<IUserService>().Use<UserService>().Ctor<string>("randomParam").Is("YourValue");
Whilst this will work, it's worth mentioning that if the parameter you're injecting is tied to any kind of business logic, configuration or even if it value's based on certain conditions then I would suggest creating a builder class that acts as a proxy (similar to this answer) and encapsulates the logic that decides the value of the string and inject that instead.
When injecting strings like this you have to be careful not to put your business logic in the wrong place.