【问题标题】:FluentValidation With Autofac使用 Autofac 进行流利验证
【发布时间】:2013-03-20 03:49:09
【问题描述】:

我们刚刚开始使用 FluentValidation 并关注这篇文章以允许我们使用我们的全球化价值观:http://fluentvalidation.codeplex.com/discussions/394471

但是,我们被困在如何获取对包含我们现有全球化值的翻译服务接口的引用。这包含在一个单独的项目中,因为它不直接与 ASP.NET MVC 耦合,因此我们不能使用 DependencyResolver。

有谁知道我们可以将 Interface 或 autofac 容器放入 TranslationServiceStringSource 类以用于获取翻译值的方法?

【问题讨论】:

    标签: c# autofac fluentvalidation


    【解决方案1】:

    我假设您在某处有一些类似于:

    var container = builder.Build();
    var resolver = new AutofacDependencyResolver(container);
    DependencyResolver.SetResolver(resolver);
    

    如果您将对该容器的引用存储在某处,我通常会在 MvcApplication 类 (global.asax.cs) 中创建一个引用:

    public static IContainer Container { get; set; }
    

    那么你可以:

    public TranslationServiceStringSource(string text) {
        _text = text;
        _translator = new MvcApplication.Container.Resolve<ITranslationService>(); 
    }
    

    虽然最好让 TranslationServiceStringSource 由 AutoFac 管理。

    【讨论】:

    • 如果你直接从容器中解析出来,实例将与容器一样长(这可能是应用程序的生命周期)
    • 最后我们创建了一个由 Autofac 管理的 IValidationsService,它允许我们在构造函数中传入翻译服务。我们不能在 MvcApplication 中有静态引用,因为它包含在一个单独的项目中,并且管理 TranslationServiceStringSource 会很棘手,因为我们在业务规则对象上使用扩展方法来添加翻译。我会给你这个尽管试图让 autofac 管理 TranslationServiceStringSource 让我想到了我认为最好的方法,或者至少是我能看到的唯一方法。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多