Skip to content

Instantly share code, notes, and snippets.

@floydpink
Created March 14, 2020 16:08
Show Gist options
  • Save floydpink/b14e7719a9eb38e80f6943d051a6edcd to your computer and use it in GitHub Desktop.
Save floydpink/b14e7719a9eb38e80f6943d051a6edcd to your computer and use it in GitHub Desktop.
Create an implementation of 'IStartupFilter' to validate all 'IValidatable' at startup
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
// reference: https://andrewlock.net/adding-validation-to-strongly-typed-configuration-objects-in-asp-net-core/#creating-a-settings-validation-step-with-an-istartupfilter
namespace MyWeb.Filters
{
public class ConfigValidationStartupFilter : IStartupFilter
{
readonly IEnumerable<IValidatable> _validatableObjects;
public ConfigValidationStartupFilter(IEnumerable<IValidatable> validatableObjects)
{
_validatableObjects = validatableObjects;
}
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
foreach (var validatableObject in _validatableObjects)
{
validatableObject.Validate();
}
//don't alter the configuration
return next;
}
}
}
namespace MyWeb.Config
{
public interface IValidatable
{
void Validate();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment