开发者

structuremap configuration change based on settings in app.config

开发者 https://www.devze.com 2022-12-28 16:34 出处:网络
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 reposit

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消