We have 2 national banks – and we gather exchange rates from there. What if we want to add more banks -or let other programmers to add their dll’s to our software to just display the exchange rates from other banks ?
Option 1: HardCode all the list
var l = new List<IExchangeRates[]>
{
new GetFirstBank()),
new GetSecondBank()),
};
Option 2: Reading from some config file the list of classes – letting DevOps to modify the config file
var l = new List<IExchangeRates[]>;
foreach(var line in File.ReadAllLines(“myListOfExchangeRates.txt”){
IExchangeRates r= Activator.CreateInstance(Type.GetType(line)) as IExchangeRates ;
l.Add ( r );
}
Option 3: Reflection – in the current assembly or in all assemblies to load the classes that implements the interface to load the data
var typeToFound = typeof(IExchangeRates);
Assembly a = Assembly.GetExecutingAssembly();
var types = a.GetTypes()
.Where(it=>it.IsPublic)
.Where(it => it.GetInterface(typeToFound.FullName)!=null)
.ToArray();
foreach(var t in types)
{
recognizes.Add(Activator.CreateInstance(t)as  IExchangeRates);
}
Option4 Load as plugins
use the library from https://github.com/natemcmaster/DotNetCorePlugins/blob/master/samples/hello-world/HostApp/Program.cs and there are 2 lines,basically:
var loader = new LoadExchangeProviders("plugins"); var exchange = loader.LoadExchangeProviders().ToArray();
Leave a Reply