JamesRandall / FunctionMonkey

Write more elegant Azure Functions with less boilerplate, more consistency, and support for REST APIs. Docs can be found at https://functionmonkey.azurefromthetrenches.com
MIT License
294 stars 50 forks source link

Add Validators via Assembly search not working #168

Open peteharrison opened 4 years ago

peteharrison commented 4 years ago

Hi Team,

Am I missing something?

I am trying to use serviceCollection.AddValidatorsFromAssemblyContaining() to effectively find all instances of my fluent validation validators and add them to the service collection as transient however it doesn't appear to pick them up.

However, if I manually add the validator to the service collection via serviceCollection.AddTransient<IValidator, LoginCommandValidator>(); it works.

Am I not using this correctly? It doesn't throw any errors just isn't picking up my validators.

AKomyshan commented 4 years ago

Hi,

I checked this behavior.

Make sure that you pass the type from the Assembly that contains inheritors of IValidator<T> (AbstractValidator<TCommand>) as first parameter.

More info: https://github.com/JamesRandall/FunctionMonkey/blob/master/Source/FunctionMonkey.FluentValidation/IServiceCollectionExtensions.cs

peteharrison commented 4 years ago

Yes I had a look at this and I copied what James had done in this article https://dev.to/jamesrandall/elegant-azure-functions-development-in-c-with-function-monkey-1ea7 by calling .AddValidatorsFromAssemblyContaining() and it didn't work?

Can you give me an example?

my validator class looks like:

class LoginCommandValidator : AbstractValidator { public LoginCommandValidator() { RuleFor(x => x.Credentials).NotNull().NotEmpty(); RuleFor(x => x.Credentials.Identifier).NotEmpty().NotNull(); RuleFor(x => x.Credentials.Password).NotEmpty().NotNull(); RuleFor(x => x.Credentials.AppId).NotEmpty().NotNull(); } }

and my function app configuration looks like

public class FunctionAppConfiguration : IFunctionAppConfiguration { public void Build(IFunctionHostBuilder builder) { builder .Setup((serviceCollection, commandRegistry) => { string SqlConnection = Environment.GetEnvironmentVariable("AuthDBConnectionString");

                serviceCollection.AddDbContext<AuthDBContext>(
                    options => options.UseSqlServer(SqlConnection))
                .AddTransient<IAuthRepository, AuthRepository>()
                .AddValidatorsFromAssemblyContaining<FunctionAppConfiguration>();

                commandRegistry.Discover<FunctionAppConfiguration>();

            })
            .DefaultHttpResponseHandler<DefaultResponseHandler>()
            .AddFluentValidation()
            .Functions(functions => functions
                .HttpRoute("v1/Login", route => route
                    .HttpFunction<Login>(HttpMethod.Post)
                )
            );
    }
}