选项模式 - 接口/抽象属性

Nik*_*efi 4 c# .net-core .net-core-configuration servicecollection

我想将以下对象与ServiceCollection中的appsettings.json数据绑定,但是我无法更改类或接口的设计:

public class TransferOptions :ITransferOptions 
{
   public IConnectionInfo Source {get;set;}
   public IConnectionInfo Destination {get;set;}
}

public class ConnectionInfo : IConnectionInfo
{
   public string UserName{get;set;}
   public string Password{get;set;}
}

public interface ITransferOptions
{
   IConnectionInfo Source {get;set;}
   IConnectionInfo Destination {get;set;}
}

public interface IConnectionInfo
{
   string UserName{get;set;}
   string Password{get;set;}
}
Run Code Online (Sandbox Code Playgroud)

这是我在appsettings.json中的数据

{
"TransferOptions":{
    "Source ":{
                 "UserName":"USERNAME",
                 "Password":"PASSWORD"
              },
    "Destination":{
                 "UserName":"USERNAME",
                 "Password":"PASSWORD"
              }
   }
}
Run Code Online (Sandbox Code Playgroud)

这是我在服务提供商上的配置:

var provider=new ServiceCollection()
.Configure<TransferOptions>(options => _configuration.GetSection("TransferOptions").Bind(options))
.BuildServiceProvider();
Run Code Online (Sandbox Code Playgroud)

这是我收到错误的部分

无法创建“IConnectionInfo”类型的实例,因为它是抽象的或接口

var transferOptions =_serviceProvider.GetService<IOptions<TransferOptions>>()
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 6

由于接口和规定的限制,您需要自己构建选项成员

var services = new ServiceCollection();

IConnectionInfo source = _configuration.GetSection("TransferOptions:Source").Get<ConnectionInfo>();
IConnectionInfo destination = _configuration.GetSection("TransferOptions:Destination").Get<ConnectionInfo>();

services.Configure<TransferOptions>(options => {
    options.Source = source;
    options.Destination = destination;
});

var provider = services.BuildServiceProvider();
Run Code Online (Sandbox Code Playgroud)