using MultiTerm.Protocols.Types;
namespace MultiTerm.Protocols.Factories;
///
/// Can create instances during runtime.
///
public class CommunicationProtocolFactory : ICommunicationProtocolFactory
{
private readonly Func> protocolFactory;
private readonly Func> settingsViewModelFactory;
///
/// Constructor of .
///
/// function that gets all registered services with Interface
/// function that gets all registered services with Interface
public CommunicationProtocolFactory(Func> protocolFactory, Func> settingsViewModelFactory)
{
this.protocolFactory = protocolFactory;
this.settingsViewModelFactory = settingsViewModelFactory;
}
///
/// Creates a new and its corresponding .
///
/// of the new
/// tuple of communication protocol and protocol settings viewmodel
public Tuple Create(ProtocolType protocolType)
{
ICommunicationProtocol protocol;
IProtocolSettingsViewModel settingsViewModel;
// get all registered ICommunicationProtocol as IEnumerable
var registeredProtocols = protocolFactory();
// get all registered IProtocolSettingsViewModel as IEnumerable
var registeredSettingsViewModel = settingsViewModelFactory();
// search for correct type of protocol implementation by ProtocolType
try
{
protocol = registeredProtocols.Where(x => x.ProtocolType == protocolType).First();
}
catch (Exception ex)
{
throw new NotImplementedException($"'{nameof(CommunicationProtocolFactory)}' cannot create " +
$"CommunicationProtocol with {nameof(ProtocolType)} {protocolType}", ex);
}
// search for correct type of settings View Model implementation by ProtocolType
try
{
settingsViewModel = registeredSettingsViewModel.Where(x => x.ProtocolType == protocolType).First();
}
catch (Exception ex)
{
throw new NotImplementedException($"'{nameof(CommunicationProtocolFactory)}' cannot create " +
$"ProtocolSettingsViewModel with {nameof(ProtocolType)} {protocolType}", ex);
}
// check if settings viewmodel also implements IProtocolSettings, which it must
if(settingsViewModel is not IProtocolSettings)
{
throw new NotImplementedException($"'{nameof(CommunicationProtocolFactory)}' cannot create " +
$"CommunicationProtocol since {settingsViewModel.GetType()} does not implement {nameof(IProtocolSettings)}.");
}
// return the filled up instances
return new Tuple(protocol, settingsViewModel);
}
}