2

我想将以下对象与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;}
}

这是我在appsettings.json中的数据

{
"TransferOptions":{
    "Source ":{
                 "UserName":"USERNAME",
                 "Password":"PASSWORD"
              },
    "Destination":{
                 "UserName":"USERNAME",
                 "Password":"PASSWORD"
              }
   }
}

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

var provider=new ServiceCollection()
.Configure<TransferOptions>(options => _configuration.GetSection("TransferOptions").Bind(options))
.BuildServiceProvider();

这是我得到错误的部分

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

var transferOptions =_serviceProvider.GetService<IOptions<TransferOptions>>()
4

2 回答 2

2

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

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();
于 2019-12-01T10:44:40.347 回答
0

接口不能直接实例化。

所以,如果你不能改变你的类的设计——也就是说,使用 ConnectionInfo 的具体实现——我猜你可以实例化 ConnectionInfo 类并将它分配给 IConnectionInfo 接口,如下所示:

public class TransferOptions : ITransferOptions 
{
   public IConnectionInfo Source { get; set; } = new ConnectionInfo();
   public IConnectionInfo Destination { get; set; } = new ConnectionInfo();
}
于 2019-12-01T10:08:04.113 回答