I'm using the Unity framework to inject a ConfigurationProvider into some of my classes via the following interface:
interface IConfigurationProvider<T>{
T GetConfiguration();
}
then, in my bootstrapper with Unity,
container.RegisterType(typeof (IConfigurationProvider<DongleConfiguration>),
typeof (DongleConfigurationProvider));
This has been a good strategy up until now & has allowed me to define different config providers for various implementations & tests. Now, I'd like one of the providers to use command line arguments to set up a config object, which requires me to pass along the args
parameter to the ctor:
class ProblematicConfigurationProvider : IConfigurationProvider<ProblematicConfiguration> {
...
public ProblematicConfigurationProvider(string[] args) { ... }
...
}
I've read that I can use ParameterOverride
to supply an optional ctor argument as such:
var configObj = container.Resolve<IConfigurationProvider<ProblematicConfiguration>>(new ParameterOverride("args"开发者_C百科, args));
However, I'm using DI "all the way" and relying on the container to resolve dependencies down the line after resolving RootObject
or whatever my top level class is. My question is, how can I now use the configObj
object I've just resolved if it's buried somewhere down deep in my dependency graph? How can I use a resolved object in another call to Resolve
? Would it be through a similar use of ParameterOverride
? Is there a way to set up the param override somewhere & have Unity use it without actually instantiating configObj
?
I would do this differently. Add a CommandLineArguments class to your project, which just wraps the command line arguments. As part of your container initialization, register that with the container:
container.RegisterInstance(new CommandLineArguments(args));
Then your ConfigurationProvider should have a dependency of CommandLineArguments, not string[]. From there, it should just resolve everything naturally "all the way down" without using the parameter overrides.
Since your command line arguments aren't going to change, this makes it a lot simpler in my opinion.
Note: I use the CommandLineArguments type because it's a lot more descriptive of what's going on. You could register the string[] directly into the container, but that would feel a little wierd to me, and possibly inject you command line arguments somewhere you don't expect.
精彩评论