Inline dependencies 依赖

时间:2021-10-11 07:56:24

应用程序中的很多组件都会依赖其他的服务组件,,很多依赖一些不合法的组件或者容器中没有的组件,例如int类型、string类型、TimeSpan类型

Windsor支持以上的场景,注册API有DependsOn方法。该方法接收一个参数(由Dependency类的静态方法返回值提供)

1. 支持静态依赖 Dependency.OnValue

var twitterApiKey = @"the key goes here"; container.Register( Component.For<ITwitterCaller>().ImplementedBy<MyTwitterCaller>() .DependsOn(Dependency.OnValue("APIKey", twitterApiKey)) );

这个例子通过名称进行依赖匹配,它将提供对应的值给MyTwitterCaller类中名为“APIKey”的属性或者构造函数参数

2.通过类型依赖

var config = new TwitterApiConfiguration { // set all the properties here... }; container.Register( Component.For<ITwitterCaller>().ImplementedBy<MyTwitterCaller>() .DependsOn(Dependency.OnValue<TwitterApiConfiguration>(config)) );

3. 设置属性 Setting up properties: Property.ForKey()

container.Register( Component.For<ICustomer>().ImplementedBy<CustomerImpl>() .DependsOn(Property.ForKey("Name").Eq("Caption Hook"), Property.ForKey("Age").Eq(45)));

4. 明确的服务依赖 Dependency.OnComponent()

container.Register( Component.For<ITransactionProcessingEngine>().ImplementedBy<TransactionProcessingEngine>() .DependsOn(Dependency.OnComponent("Logger", "secureLogger")) );

5. 依赖配置文件 appSettings dependencies: Dependency.OnAppSettingsValue()

container.Register( Component.For<ITwitterCaller>().ImplementedBy<MyTwitterCaller>() .DependsOn(Dependency.OnAppSettingsValue("timeout", "twitterApiTimeout")) );

6. 

container.Register( Component.For<MainViewModel>() .DependsOn(Dependency.OnResource<MyApp.Properties.Resources>("DisplayName", "MainWindowTitle")) );

Embedded resource dependencies: Dependency.OnResource()

7. Supplying dynamic dependencies

container.Register( Component.For<ClassWithArguments>() .LifestyleTransient() .DynamicParameters((k, d) => d["createdTimestamp"] = DateTime.Now) );

castle windsor学习-----Inline dependencies 依赖