How do i Inject a custom service into a custom DataAnnotation?
I am using Umbraco version 8.9.1 and have setup a very simple test to get it going.
Interface
public interface ICustomService
{
bool DoSomeThing(object value);
}
Service
using Umbraco.Core.Logging;
public class CustomService : ICustomService
{
private readonly ILogger _logger;
public CustomService(ILogger logger)
{
_logger = logger;
}
public bool DoSomeThing(object value)
{
return value == null;
}
}
DataAnnotation (this do not work)
using System.ComponentModel.DataAnnotations;
public class CustomValidationAttribute : ValidationAttribute
{
private readonly ICustomService CustomService;
public CustomValidationAttribute(ICustomService customService)
{
CustomService = customService;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if(CustomService.DoSomeThing(value))
{
return ValidationResult.Success;
}
return new ValidationResult(ErrorMessage);
}
}
IUserComposer (Can i do something else here?)
using Umbraco.Core.Composing;
public class Installer : IUserComposer
{
public void Compose(Composition composition)
{
composition.Register<ICustomService, CustomService>();
}
}
Inject custom service into custom DataAnnotation
Hi all.
How do i Inject a custom service into a custom DataAnnotation?
I am using Umbraco version 8.9.1 and have setup a very simple test to get it going.
Interface
Service
DataAnnotation (this do not work)
IUserComposer (Can i do something else here?)
Any thoughts and help is very appreciated.
This works. But is it the right way to do it?
It seems like you also could use the
validationContext
to get a service by usingMicrosoft.Extensions.DependencyInjection
likeis working on a reply...