vendredi 13 août 2021

In C#, how can I add instances of FluentValidation using reflection?

Currently, I’m adding validators in the Startup.cs like:

public void ConfigureContainer(ContainerBuilder builder)
        {
            Register<Signer, SignerValidator>(builder);
            Register<ContractBase, ContractBaseValidator>(builder);
            Register<ContractGridop, ContractGridopValidator>(builder);
            Register<ContractSepa, ContractSepaValidator>(builder);
            Register<ContractVollmacht, ContractVollmachtValidator>(builder);
        }

        private static void Register<TType, TValidator>(
                ContainerBuilder builder
            ) =>
             builder.RegisterType<TValidator>()
                    .As<IValidator<TType>>()
                    .SingleInstance();

It occurs to me:

  1. It should not be necessary to pass both TType and TValidator because every instance of TValidator is defined in terms of TType.

  2. Doing it this way is not only redundant but dangerous because there is no guarantee that TType will correctly correspond to TValidator.

  3. There should be a way for the system to automatically discover what validators exist and then automatically add them (similar to how the API controllers are being added).

How can I do this?





Aucun commentaire:

Enregistrer un commentaire