Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: IValidator additional property

$
0
0
Jeremy,
I want the DI layer to inject a validator instance.   Because I want it to inject a particular validator instance.   So, I to use IValidator<T>. ...like this:
public SomeConstructor(IValidator<SomeViewModel> viewModelValidator)

What happens is I get the above class injected and I end up having to write bad code like this:
            var validator = (AbstractValidator<SomeViewModel>)viewModelValidator;
            var validatorDescriptor = (ValidatorDescriptor<SomeViewModel>)validator.CreateDescriptor();
Of course that is a lot of repeating myself about a type (SomeViewModel) that I should already know.


So, I thought I would just create my own class derived from AbstractValidator. I could then have that implement my own ICustomValidator interface and register all the classes with DI and get that injected. To get rid of the first type, I can create my own interface and hook everything up to DI and will not need that cast.

To get rid of the validatorDescriptor cast, I wanted to create a CreateTypedDesriptor method that looks like
        public ValidatorDescriptor<T> CreateTypedDescriptor()
        {
            return new ValidatorDescriptor<T>(nestedValidators);
        }
Cannot do that...because nestedValidators is a private member of AbstractValidator...ugh. Can this be changed, or do I have to copy and paste the your entire abstractvalidator into my new class for this change?

Ideally, the IValidator<T> would implement the CreateTypedDescriptor<T> CreateTypedDescriptor() interface as an added item...??

Then trying to use a simple AbstractValidator derrived class:
    public abstract class EnhancedValidator<T> : AbstractValidator<T>
    {
    }
Just the act of declaring the above class cause the DI to crash with EnhancedValidator1[T] is not assignable to FluentValidation.IValidator1.
The code I used for registration was:
            AssemblyScanner findValidatorsInAssembly = AssemblyScanner.FindValidatorsInAssembly(typeof(MvcApplication).Assembly);
            foreach (AssemblyScanner.AssemblyScanResult item in findValidatorsInAssembly)
            {
                builder.RegisterType(item.ValidatorType).As(item.InterfaceType);
            }
Any thoughts on any of these walls I hit Jeremy? Thanks for looking.

Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>