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:
It should not be necessary to pass both TType
and TValidator
because every instance of TValidator
is defined in terms of TType
.
Doing it this way is not only redundant but dangerous because there is no guarantee that TType
will correctly correspond to TValidator
.
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?
With thanks to @Jamiec and a colleague, I now understand all I need to do is:
services.AddFluentValidation(c => c.RegisterValidatorsFromAssemblyContaining<Startup>());
... assuming all my validators live in the same project as Startup.cs