gpt4 book ai didi

asp.net-mvc - 如何自动向 Unity 注册所有流畅验证器?

转载 作者:行者123 更新时间:2023-12-02 04:54:29 25 4
gpt4 key购买 nike

现在我已经在我的应用程序中连接并构建了验证器,但是每次添加新的验证器时,我们都需要手动进入 Unity 配置并注册类型。我想自动执行此操作,就像 this blog post describes doing with StructureMap 一样,仅适用于 Unity。

现在我有这样的东西:

    // in global.asax.cs
protected void Application_Start(Object sender, EventArgs e)
{
// some irrelevant registrations (area registrations, route config, etc)

var container = new UnityContainer();
UnityConfig.RegisterComponents(container);
FluentValidationModelValidatorProvider.Configure(c => c.ValidatorFactory = new UnityValidatorFactory(container));
}

public class UnityValidatorFactory : ValidatorFactoryBase
{
private readonly IUnityContainer container;

public UnityValidatorFactory(IUnityContainer container)
{
this.container = container;
}

public override IValidator CreateInstance(Type validatorType)
{
if (container.IsRegistered(validatorType))
{
return container.Resolve(validatorType) as IValidator;
}

return null;
}
}

public static class UnityConfig
{
public static void RegisterComponents(IUnityContainer container)
{
container.RegisterTypes(
AllClasses.FromAssemblies(
Assembly.GetAssembly(typeof (UnityConfig)),
WithMappings.FromMatchingInterface, WithName.Default);

RegisterValidators(container);

DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

private static void RegisterValidators(IUnityContainer container)
{
container.RegisterType<IValidator<MyFirstViewModel>, MyFirstViewModelValidator>();
container.RegisterType<IValidator<MySecondViewModel>, MySecondViewModelValidator>();
}
}

我所拥有的正在工作,但每次创建新的验证器时,我都必须继续向 RegisterValidators() 添加注册。有没有办法可以将其设置为自动检测和注册所有验证器?

最佳答案

一旦我弄清楚我在做什么,这就变得相当容易,这也许可以解释为什么谷歌搜索答案没有产生任何结果。我重写了RegisterValidators如下:

private static void RegisterValidators(IUnityContainer container)
{
var validators = AssemblyScanner.FindValidatorsInAssemblyContaining<OneOfMyValidators>();
validators.ForEach(validator => container.RegisterType(validator.InterfaceType, validator.ValidatorType));
}

关于asp.net-mvc - 如何自动向 Unity 注册所有流畅验证器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25185272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com