structuremap configuration change based on settings in app.config
I am using structuremap in my project. To inject different implementation of a repository, I want to have a switch in app.config which changes all real implementation of a repository to a mock repositories.
Lets say IRepository has two implementations RealRepository and MockRepository
ForRequestedType()开发者_开发知识库 .TheDefaultIsConcreteType();
I want to have a switch in app.config / web.config say (Mock=1), which changes all real repositories implementation to
ForRequestedType() .TheDefaultIsConcreteType();
I don't want to write whole plugin definition in app.config, just want one switch, how do I implement this?
Although it may look strange, remember that your StructureMap registration code is still just C#, and you have the full power of the language available to you. Which means you are free to use an "if" statement when needed. Since your condition is based on app.config, you don't need to account for the value changing at runtime - you can safely use the value at startup configuration time.
if (appConfigIndicatesMockMode()){
ForRequestedType<IRepository>().TheDefaultIsConcreteType<MockRepository>()
} else {
ForRequestedType<IRepository>().TheDefaultIsConcreteType<RealRepository>()
}
where appConfigIndicatesMockMode()
is a method that reads your app.config setting in the usual way and returns true or false.
精彩评论