AutoFac文档3(转载)
2013-08-29 16:54
197 查看
目录
开始Registering components
控制范围和生命周期
用模块结构化Autofac
xml配置
与.net集成
深入理解Autofac
指导
关于
词汇表
服务类型,名称和键
同一个服务的不同实现可以以类型,名称和键区分。autofac提供三种典型的方式区分服务。
按类型
类型是描述服务的基本方法1 | builder.Register<OnlineState>().As<IDeviceState>(); |
1 | var r = container.Resolve<IDeviceState>(); |
按名字
服务可以进一步按名字识别。使用这种技术时,用 Named()注册方法代替As():1 | builder.Register<OnlineState>().Named<IDeviceState>( "online" ); |
1 | var r = container.ResolveNamed<IDeviceState>( "online" ); |
指定名字的服务其实是指定键的服务的简单版本,所以在下一节讲到的技术也同样适用于指定名字的服务。
按键
在一些情况下使用字符串做component的名字很方便,但是在另外一些情况下我们需要使用其他类型做键。按键指定服务提供了这种机制。比如,使用一个枚举来描述设备的不同状态
1 | public enum DeviceState { Online, Offline } |
1 | public class OnlineState : IDeviceState { } |
1 2 3 4 | var builder = new ContainerBuilder(); builder.RegisterType<OnlineState>().Keyed<IDeviceState>(DeviceState.Online); builder.RegisterType<OfflineState>().Keyed<IDeviceState>(DeviceState.Offline); // Register other components here |
可以使用ResolveKeye()进行显式检索。
1 | var r = container.ResolveKeyed<IDeviceState>(DeviceState.Online); |
在之前的2.3版本中, ResolveKeyed()只是Resolve()的简单重载。
使用索引检索
Autofac.Features.Indexed.IIndex<K,V>是autofac自动实现的一个关联类型。component可以使用IIndex<K,V>作为参数的构造函数从基于键的服务中选择需要的实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class Modem : IHardwareDevice { IIndex<DeviceState, IDeviceState> _states; IDeviceState _currentState; public Modem(IIndex<DeviceState, IDeviceState> states) { _states = states; SwitchOn(); } void SwitchOn() { _currentState = _states[DeviceState.Online]; } } |
相关文章推荐
- AutoFac文档8(转载)
- AutoFac文档12(转载)
- AutoFac文档7(转载)
- AutoFac文档11(转载)
- AutoFac文档6(转载)
- AutoFac文档5(转载)
- AutoFac文档4(转载)
- AutoFac文档2(转载)
- AutoFac文档(转载)
- AutoFac文档10(转载)
- AutoFac文档14(转载)
- AutoFac文档9(转载)
- AutoFac文档13(转载)
- 如何从sun公司官网下载java API文档(转载)
- 【转载】互联网常见Open API文档资源
- 另一个.NET上的文档数据库Raven[转载]
- 文档上传和提取内容 (转载)
- 转载:DoxyGen文档之五
- 软件需求分析文档模版(转载自国家计算机标准和文件模板)
- 转载:C#如何实现把word文档内的图片提取出来