Сначала определите общий интерфейс
public interface IExtractor
{
string RecordType { get; }
string ErrorMessage { get; }
string GetValue(object record);
}
Затем создайте реализации
class MxRecordExtractor : IExtractor
{
public string RecordType => "Mx";
public string ErrorMessage => DomainRegistrationCore.Models.DomainRecordType.MX;
public string GetValue(object record)
{
return ((Microsoft.Graph.DomainDnsMxRecord)record).MailExchange;
}
}
class VerificationRecordExtractor : IExtractor
{
public string RecordType => "Txt";
public string ErrorMessage => DomainRegistrationCore.Models.DomainRecordType.TXT;
public string GetValue(object record)
{
return ((Microsoft.Graph.DomainDnsTxtRecord)record).Text;
}
}
Позже создайте закрытую абстрактную версию метода:
private async Task<string> ExtractForDomainAsync(string domain, IExtractor extractor)
{
try
{
var records = (await _graphClient.Domains[domain].VerificationDnsRecords.Request().GetAsync());
string extractedValue = String.Empty;
foreach (var record in records)
{
if (record.RecordType == extractor.RecordType)
{
extractedValue = extractor.GetValue(record);
break;
}
}
if (String.IsNullOrWhiteSpace(extractedValue))
throw new DomainRecordNotFoundException(extractor.ErrorMessage);
return extractedValue;
}
catch (ServiceException graphEx)
{
if (graphEx.StatusCode == System.Net.HttpStatusCode.NotFound)
{
throw new DomainNotFoundException();
}
throw new UnknownException(graphEx.StatusCode, graphEx.Error.Message);
}
}
Наконец измените существующие методы наиспользуйте наш общий метод:
public Task<string> GetMxRecordForDomainAsync(string domain)
{
return ExtractForDomainAsync(domain, new MxRecordExtractor());
}
public Task<string> GetVerificationRecordForDomainAsync(string domain)
{
return ExtractForDomainAsync(domain, new VerificationRecordExtractor());
}