Open Closed

Exception when trying to access localization service from DTO's Validate method from IValidatableObject #3862


User avatar
0
balessi75 created

Abp Commercial 5.2 / EF Core / Blazor Server

Hi, we have a DTO which implements IValidatbleObject and in our Validate method and we are attempting to localize errors by doing the following...

 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    var l = validationContext.GetRequiredService<IStringLocalizer<TimepieceResource>>();

    if (StartTime != null && EndTime != null && StartTime >= EndTime)
    {
        yield return new ValidationResult(l["Validation:StartTimeGreaterThanEndTime"].Value,  new[] { nameof(StartTime) });
    }

}

The problem though is that, the GetRquiredService call exceptions out with the following...

System.InvalidOperationException: No service for type 'Microsoft.Extensions.Localization.IStringLocalizer 1[FM.Timepiece.Localization.TimepieceResource] has been registered. The call is not displaying properly in the code block above... it's called as follows... var l = validationContext.GetRequiredService<IStringLocalizer<TimepieceResource>>();

Any help narrowing this down is greatly appreciated.

Regards, balessi75


3 Answer(s)
  • User Avatar
    0
    malik.masis created

    Hi,

    I think you follow this documentation

    public class YourDto : IValidatableObject
    { 
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var l = validationContext.GetRequiredService< IStringLocalizer< YourResource>>();
        }
    }
    

    This part of the code should work properly. Also, you can have a look here.

    Regards

  • User Avatar
    0
    balessi75 created

    Hi malik.masis,

    When we execute the following (as shown in Abp documentation)..

    var l = validationContext.GetRequiredService<IStringLocalizer<AppNameResource>>();

    We receive the following exception at runtime...

    System.InvalidOperationException: No service for type 'Microsoft.Extensions.Localization.IStringLocalizer 1[FM.Timepiece.Localization.TimepieceResource] has been registered.

    The call to GetRequiredService is initiated in the Validate method of our Dto located in the Application.Contracts project.

    Any idea why this method call is not returning the service and erroring out for us?

  • User Avatar
    0
    malik.masis created

    Hi,

    It seems like an IOC issue because of the absence of the required module.

    I think it's a similar issue. Could you have a look at it, please?

    Also, there is detailed documentation regarding DI.

    Hopefully, these help you.

    Regards

Made with ❤️ on ABP v8.2.0-preview Updated on March 25, 2024, 15:11