I want to bind the following object with the appsettings.json data in ServiceCollection, however I cannot change the design of the class or the 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;}
}
this is my data in the appsettings.json
{
"TransferOptions":{
"Source ":{
"UserName":"USERNAME",
"Password":"PASSWORD"
},
"Destination":{
"UserName":"USERNAME",
"Password":"PASSWORD"
}
}
}
Here is my config on service provider :
var provider=new ServiceCollection()
.Configure<TransferOptions>(options => _configuration.GetSection("TransferOptions").Bind(options))
.BuildServiceProvider();
This is the part I get error
Cannot create instance of type 'IConnectionInfo' because it is either abstract or an interface:
var transferOptions =_serviceProvider.GetService<IOptions<TransferOptions>>()
Because of the interfaces and the stated limitations you will need to build up the options members yourself
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();