Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Options pattern - Interface/Abstract property

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>>()
like image 895
Sara NikitaUsefi Avatar asked Sep 20 '25 03:09

Sara NikitaUsefi


1 Answers

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();
like image 174
Nkosi Avatar answered Sep 22 '25 15:09

Nkosi