Options pattern - Interface/Abstract property

1.9k Views Asked by At

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

There are 2 best solutions below

0
On BEST ANSWER

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

An interface cannot be instantiated directly.

So, if you can't change your class' design - that is, use the concrete implementation of ConnectionInfo - I guess that you could instantiate the ConnectionInfo class and assign it to the IConnectionInfo interface like so:

public class TransferOptions : ITransferOptions 
{
   public IConnectionInfo Source { get; set; } = new ConnectionInfo();
   public IConnectionInfo Destination { get; set; } = new ConnectionInfo();
}