使用选项初始化服务
一个服务可以注入另一个服务中,也可以用来初始化一个带有选项的服务。不能使用服务的构造函数定义非服务协定来初始化,因为容器不知道如何初始化它。服务是必要的,但是为了传递服务选项,还可以使用已经可用于.Net Core的服务。
示例DIWithOptions使用以下的包和命名空间
包
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Options
命名空间
System
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Options
代码文件 DIWithOptions/GreetingServiceOptions.cs
public class GreetingServiceOptions
{
public string From {
get;set;}
}
可以指定带有IOptions<T>参数的构造函数,来传递服务选项。前面定义的GreetingServiceOptions是用于IOptions的泛型类型。
代码文件DIWithOptions/GreetingService.cs
class GreetingService : IGreetingService
{
private readonly string _from;
public GreetingService(IOptions<GreetingServiceOptions> options)
=> _from = options.Value.From;
public string Greet(string name) => $"Hello,{name},Greeting from {_from}";
}
注意
IOptions接口和用于选项的服务在NuGet包Microsoft.Extensions.Options中实现
为了便于使用DI容器注册服务,定义了扩展方法AddGreetingService。该方法扩展了IServiceCollection接口,并允许通过委托传递GreetingServiceOptions。在实现代码中,Configure方法用于通过IOptions接口指定配置,Configure方法是NuGet包Microsoft.Extensions.Options中IServiceCollection的扩展方法。
代码文件 DIWithOptions/GreetingServiceExtensions.cs
public static class GreetingServiceExtensions
{
public static IServiceCollection AddGreetingService(
this IServiceCollection collection,
Action<GreetingServiceOptions> configuration)
{
if (collection == null)
throw new ArgumentNullException