samedi 17 avril 2021

Design pattern for critical parameter passing to method

Thinking about elegant solutions for critical parameter passing (as in e.g. security relevant parameters) when resolving a single instance (e.g. a repository) via DI.

The goals/restrictions are:

  • Can only resolve a single instance of the repository, because resolving one for every critical parameter might require thousands of instances.
  • The critical parameter should be easy to audit, i.e. one can search easily across the code base and validate them (e.g. via "Find all references").

One such elegant way would be fluent method chaining as in the below example inside Create. I just don't see a way of wiring that up.

The hard way would be to pass that as the first parameter to every method, which just ends up with a lot of extra parameters in a large code base.

Are there any obvious design patterns to solve this challenge?

public class MyService : IMyService
{
    private readonly IMyRepository _myRepository;

    public MyService(IMyRepository myRepository)
    {
        _myRepository = myRepository;
    }

    public async Task Create(TenantId tenantId, MyDto dto)
    {
        _myRepository.UsingTenant(tenantId).Create(dto);
        // OR
        _myRepository.UsingDefaultTenant().Create(dto);
    }
}

Aucun commentaire:

Enregistrer un commentaire