[Autofac]服务类型、 名称和键

  TypedNamedAndKeyedServices   
Many implementations of the same service can be differentiated using names and keys.
同一服务的多个实现可以使用名称和键来区分。 
Autofac2
Updated   Aug 17, 2010  by   nicholas...@gmail.com

Autofac provides three typical ways to identify services.

Autofac 提供了3种典型的方式来标识服务。

By Type 按类型

The default method of describing a service is as a type.

描述服务的默认方法是把他当作一个特定的类型。

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

This example associates the IDeviceState typed service with the OnlineState component. Instances of the component can be retrieved using the service type with the Resolve() method:

这个例子把IDeviceState类型的服务和OnlineState组件联系起来。组件实例可以通过Resolve() 方法并使用服务类型来获得。

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

Typed services also work with Autowiring.

类型服务在自动装备中也同样有效。

By Name 按名称

Services can be further identified using a service name. Using this technique, the Named() registration method replaces As().

服务可以进一步使用名称来标识。这个技术通过使用Named()注册方法来替代As()方法。

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

To retrieve a named service, the ResolveNamed() method is used:

要获取一个命名服务的实例,可以使用ResolveNamed() 方法。

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

In versions of Autofac prior to 2.3, ResolveNamed() is simply an overload of Resolve().

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

Named services are simply keyed services that use a string as a key, and so the techniques described in the next section apply equally to named services.

命名服务使用字符串来当作键值,它其实是键值服务的简单版本。所以下节描述的技术也同样适用于命名服务。

By Key 按键值

Using strings as component names is convenient in some cases, but in others we may wish to use keys of other types. Keyed services provide this ability.

在某些情况下,使用字符串作为组件的名称是很方便的。但在另外一些情况中,我们可能希望使用其他类型来作为键值。键值服务提供这种功能。

For example, an enum may describe the different device states in our example:

例如使用枚举来描述设备的不同状态。

public enum DeviceState { Online, Offline }

Each enum value corresponds to an implementation of the service:

每个枚举值和一个服务实现相对应:

public class OnlineState : IDeviceState { }

The enum values can then be registered as keys for the implementations as shown below.

可以向下面这样使用枚举值注册为服务的实现。

var builder = new ContainerBuilder();
builder.RegisterType<OnlineState>().Keyed<IDeviceState>(DeviceState.Online);
builder.RegisterType<OfflineState>().Keyed<IDeviceState>(DeviceState.Offline);
// Register other components here

Resolving Explicitly 显示检索

The implementation can be resolved explicitly with ResolveKeyed():

服务实例可以使用 ResolveKeyed()来显示取得:

var r = container.ResolveKeyed<IDeviceState>(DeviceState.Online);

This does however result in using the container as a Service Locator, which is discouraged. As an alternative to this pattern, the IIndex type is provided.

但是,这会导致把容器当作服务定位器来使用,而这是不提倡的。Autofac提供了IIndex类型来作为这一模式的替代方案。

In versions of Autofac prior to 2.3, ResolveKeyed() is simply an overload of Resolve().

在Autofac之前的2.3版本中,ResolveKeyed() 方法只是Resolve().方法的简单重载。

Resolving with an Index 使用索引检索

Autofac.Features.Indexed.IIndex<K,V> is a relationship type that Autofac implements automatically. Components that need to choose between service implementations based on a key can do so by taking a constructor parameter of type IIndex<K,V>.

Autofac.Features.Indexed.IIndex<K,V>是Autofac自动实现的一个关系类型。通过键值选取的组件实现,也可以通过使用IIndex<K,V>作为构造函数参数来取得。

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];
    }
}

In the SwitchOn() method, the index is used to find the implementation of IDeviceState that was registered with the DeviceState.Online key.

SwitchOn()  方法中,使用索引来取得通过 DeviceState.Online键值注册的IDeviceState的实现。
Autofac是一个流行的.NET依赖注入框架,它简化了应用程序服务之间的依赖关系管理。在Autofac中,"服务注册"是指将组件(通常是类、接口或实现了某些特性的服务)添加到容器中,以便将来能够通过其名称自动创建实例。 程序级别的服务注册通常发生在`Program.cs`文件中,使用Autofac的`ContainerBuilder`类。以下是一个简单的示例: ```csharp using Autofac; public class Program { // 这里是全局的依赖注入容器初始化 static IContainer ConfigureServices(IServiceCollection services) { var builder = new ContainerBuilder(); // 注册服务 builder.RegisterType<MyService>().As<IMyInterface>(); builder.RegisterType<AnotherService>(); // 使用IServiceCollection的扩展方法添加其他DI配置 // 如果有外部库依赖注入,也在这里添加 // 应用生命周期结束后需要构建并返回容器 return builder.Build(); } public static async Task Main(string[] args) { using var serviceScope = ConfigureServices(services).BeginLifetimeScope(); // 创建一个新的服务范围 var myService = serviceScope.Resolve<IMyInterface>(); // 获取依赖项实例 await myService.ExecuteSomeTask(); } } ``` 在这个例子中,`ConfigureServices`方法负责配置服务,然后在`Main`函数中使用`BeginLifetimeScope`创建一个服务范围,该范围包含了所有已经注册的服务实例。当你在`Resolve`方法中请求`IMyInterface`时,Autofac会根据注册信息找到合适的实现并返回。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值