jim crown
jim crown

Reputation: 483

Logging from validator class

I have a simple class as follows used in web API. As you can see it has a validator applied via attribute

[CustomerNameValidator]
public class Customer
{
    public string CustomerName { get; set; }
}

Validator class looks like following

public class CustomerNameValidatorAttribute : ValidationAttribute
{

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        Customer customer = (Customer)validationContext.ObjectInstance;

        if ( string.IsNullOrEmpty(customer.CustomerName))
        {
            return new ValidationResult("Invalid customer Name");
        }


        return ValidationResult.Success;
    }
}

I want to add some logging in the IsValid method. I am using logging in other places that is setup using Startup class as follows.

public Startup(IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();


    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    loggerFactory.AddNLog();
}

How can logger could be used in the validation attribute class?

Upvotes: 3

Views: 1199

Answers (1)

Henk Mollema
Henk Mollema

Reputation: 46581

The ValidationContext is populated with the RequestServices property of the HttpContext (an IServiceProvider instance). This means you can resolve services from it using the GetService method on ValidationContext.

For example:

var logger = (ILogger<CustomerNameValidatorAttribute>)validationContext.GetService(typeof(ILogger<CustomerNameValidatorAttribute>));

Upvotes: 6

Related Questions