上篇已经学习了Windsor的快速入门,框架的配置只需要两步,本篇学习下这个两步配置针对特定场景的自定义的配置,我只学习了代码的配置,对于XML的配置可以参考官方文档http://docs.castleproject.org/Windsor.XML-Registration-Reference.ashx。
安装的配置
安装的配置比较简单,无非是寻找安装类,并执行安装并获取容器,所有的安装类都需要继承自IWindsorInstaller,此接口规定了方法如下:
void Install(IWindsorContainer container, IConfigurationStore store)此方法用于执行容器里具体类的注册,类注册将在下面学习。首先看看安装的配置:
WindsorContainer _container = new WindsorContainer(); _container.Install( FromAssembly.This(), //FromAssembly.Named("CastleWindsor"), //FromAssembly.Containing<ServicesInstaller>(), //FromAssembly.InDirectory(new AssemblyFilter("Extensions")), //FromAssembly.Instance(this.GetPluginAssembly()) );
实现类的配置
实现类的配置多种多样,根据实际需求可组合出不同的配置方式,以下就学习下一些常见的配置,高级配置可自行参考官方文档http://docs.castleproject.org/Windsor.Fluent-Registration-API-Extensions.ashx
要想配置实现类到容易必须新建一个安装类并在安装类的install方法下配置,如下:
<pre name="code" class="csharp"> public class ChargeInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { //container.Register( // Component.For<IPrinter>().ImplementedBy<WenZhouPrinter>(), // Component.For<ICharge>().ImplementedBy<WenZhouCharge>()); //container.Register(Classes.FromThisAssembly().InNamespace("CastleWindsor.IEntity").WithService.DefaultInterfaces()); WenZhouPrinter wz = new WenZhouPrinter(); container.Register( Component.For<LoggingInterceptor>().LifeStyle.Transient, Component.For<IFactory>().ImplementedBy<PrintFactory>(), Component.For<IPrinter>().UsingFactoryMethod(p => p.Resolve<IFactory>().GetPrint()), Component.For<ICharge>().ImplementedBy<WenZhouCharge>() .DependsOn(Dependency.OnValue("twitterApiKey", "123")) ); //继承两个接口 // container.Register( // Component.For<IUserRepository, IRepository>() // .ImplementedBy<MyRepository>() //); //简单工厂 //container // .Register( // Component.For<IMyService>() // .UsingFactoryMethod( // () => MyLegacyServiceFactory.CreateMyService()) // ); // 泛型配置 //container.Register( // Component.For(typeof(IRepository<>) // .ImplementedBy(typeof(NHRepository<>) //); //实体生命周期 //container.Register( // Component.For<IMyService>() // .ImplementedBy<MyServiceImpl>() // .LifeStyle.Transient //.Named("myservice.default") // ); //取先注册的 //container.Register( // Component.For<IMyService>().ImplementedBy<MyServiceImpl>(), // Component.For<IMyService>().ImplementedBy<OtherServiceImpl>() //); //强制取后注册的 //container.Register( // Component.For<IMyService>().ImplementedBy<MyServiceImpl>(), // Component.For<IMyService>().Named("OtherServiceImpl").ImplementedBy<OtherServiceImpl>().IsDefault() //); //注册已经存在的 //var customer = new CustomerImpl(); //container.Register( // Component.For<ICustomer>().Instance(customer) // ); } }
配置中可以使用UsingFactoryMethod来将对应的接口的工厂方法注册到容器中,容器可通过该工厂方法获取实现类,以上分别有简单工厂和工厂方法的配置。
通过DependsOn(Dependency.OnValue("twitterApiKey", "123")可向实现类的字段twitterApiKey注入”123“字符串值。
通过设置IsDefault来规定多个实现类的默认获取过来的类。
原文地址:http://blog.csdn.net/eye_cng/article/details/44277371