gpt4 book ai didi

c# - 选项模式 - 接口(interface)/抽象属性

转载 作者:行者123 更新时间:2023-12-05 02:58:22 26 4
gpt4 key购买 nike

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

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();

这是我出错的部分

Cannot create instance of type 'IConnectionInfo' because it is either abstract or an interface:

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

最佳答案

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

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();

关于c# - 选项模式 - 接口(interface)/抽象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59124184/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com