lundi 14 janvier 2019

What pattern to use for init value

I have a service, which works with external resource (Microsoft Graph):

public class Office365DomainService : IOffice365DomainService
{
    private GraphServiceClient _graphClient;

    public async Task AddDomainAsync(string domain)
    {
        await _graphClient.Domains.Request().AddAsync(new Microsoft.Graph.Domain { Id = domain });
    }

    public async Task<string> GetMxRecordForDomainAsync(string domain)
    {
        var collection = await _graphClient.Domains[domain].ServiceConfigurationRecords.Request().GetAsync();
        return String.Empty;
    }

    public async Task<string> GetVerificationRecordForDomainAsync(string domain)
    {
        var records = (await _graphClient.Domains[domain].VerificationDnsRecords.Request().GetAsync());
        string verificationText = String.Empty;

        foreach (var record in records)
        {
            if (record.RecordType == "Txt")
            {
                verificationText = ((Microsoft.Graph.DomainDnsTxtRecord)record).Text;
                break;
            }
        }
        return verificationText;
    }

    public async Task VerifyDomainAsync(string domain)
    {
        await _graphClient.Domains[domain].Verify().Request().PostAsync();
    }
}

_graphClient should be init with access_token, but I want to have lazy loading, therefore I don't want to add it to constructor. Ok, one solution is add a property:

    public string AccessToken { set => _graphClient = (new GraphSdkHelper()).GetAuthenticatedClient(value); }

It works fine, if we remember to set AccessToken before calling any method. But if we forget to do it? The best way it is to call getting access_token by another service if this _graphClient is not init. How to do it carefully?

Aucun commentaire:

Enregistrer un commentaire