zoukankan      html  css  js  c++  java
  • AutoFac文档3(转载)

    目录

    1. 开始
    2. Registering components
    3. 控制范围和生命周期
    4. 用模块结构化Autofac
    5. xml配置
    6. 与.net集成
    7. 深入理解Autofac
    8. 指导
    9. 关于
    10. 词汇表

    服务类型,名称和键

    同一个服务的不同实现可以以类型,名称和键区分。

    autofac提供三种典型的方式区分服务。

    按类型

    类型是描述服务的基本方法

    1
    builder.Register<OnlineState>().As<IDeviceState>();

    这个例子将IDeviceState 类型的服务和OnlineState 的component联系起来。可以用这个服务的类型来检索OnlineState的实例:

    1
    var r = container.Resolve<IDeviceState>();

    指定类型的服务在自动装配中也会起作用。

    按名字

    服务可以进一步按名字识别。使用这种技术时,用 Named()注册方法代替As():

    1
    builder.Register<OnlineState>().Named<IDeviceState>("online");

    使用 ResolveNamed()检索指定名字的服务:

    1
    var r = container.ResolveNamed<IDeviceState>("online");

    在之前的2.3版本中,ResolveNamed()只是Resolve()的简单重载。

    指定名字的服务其实是指定键的服务的简单版本,所以在下一节讲到的技术也同样适用于指定名字的服务。

    按键

    在一些情况下使用字符串做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);

    这么做导致容器被当做 Service Locator使用,这是不被推荐的。应该使用IIndex type替代。

    在之前的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];
        }
    }

    在SwitchOn方法中。使用索引从前面用DeviceState.Online做键注册的IDeviceState的实现。

  • 相关阅读:
    hosts 本机DNS域名解析
    五步搞定Android开发环境部署——非常详细的Android开发环境搭建教程
    OracleBulkCopy
    第三方登录(QQ登录)开发流程详解
    Asp.net MVC中Html.Partial, RenderPartial, Action,RenderAction 区别和用法
    MVC Return View() 和 Return PartialView()的区别
    如何选择Html.RenderPartial和Html.RenderAction
    C# Dictionary和Dynamic类型
    css01入门小例子
    html03表单
  • 原文地址:https://www.cnblogs.com/sandea/p/3289938.html
Copyright © 2011-2022 走看看