使用DI框架进行本地化-好主意吗? [英] Localization using a DI framework - good idea?

查看:54
本文介绍了使用DI框架进行本地化-好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个本地化和国际化的Web应用程序.我想到我可以使用依赖注入框架来做到这一点.假设我声明了一个接口ILocalResources(在此示例中使用C#,但这并不是很重要):

interface ILocalResources {
    public string OkString { get; }
    public string CancelString { get; }
    public string WrongPasswordString { get; }
    ...
}

并创建此接口的实现,我需要支持的每种语言都有一个.然后,我将设置自己的DI框架以静态或动态方式实例化适当的实现(例如,基于请求的浏览器的首选语言).

出于某种原因,我不应该使用DI框架吗?我能发现的唯一异议是,这可能有点过大,但是如果我无论如何在Web应用程序中使用DI框架,我是否也可以将其用于国际化?

解决方案

如果您不能使用现有的资源框架(如ASP.Net中内置的框架)而必须构建自己的资源框架,那么我会假设您在某个时候将需要公开提供本地化资源的服务.

DI框架用于处理服务实例化.您的本地化框架将公开提供本地化的服务.为什么框架不应该提供该服务?

这里不使用DI就像是说:我正在构建CRM应用程序,但是不能使用DI,因为DI不是为客户关系管理而构建的."

因此,是的,如果您已经在其余的应用程序中使用了DI,那么IMO将其不用于处理本地化的服务将是错误的.

I am working on a web application which I need to localize and internationalize. It occurred to me that I could do this using a dependency injection framework. Let's say I declare an interface ILocalResources (using C# for this example but that's not really important):

interface ILocalResources {
    public string OkString { get; }
    public string CancelString { get; }
    public string WrongPasswordString { get; }
    ...
}

and create implementations of this interface, one for each language I need to support. I would then setup my DI framework to instantiate the proper implementation, either statically or dynamically (for example based on the requesting browsers preferred language).

Is there some reason I shouldn't be using a DI framework for this sort of thing? The only objection I could find myself is that it might be a bit overkill, but if I'm using a DI framework in my web app anyway, I might as well use it for internationalization as well?

解决方案

If you cannot use an existing resource framework (like that built into ASP.Net) and would have to build your own, I will assume that you at some point will need to expose services that provide localized resources.

DI frameworks are used to handle service instantiation. Your localization framework will expose services providing localization. Why shouldn't that service be served up by the framework?

Not using DI for its purpose here is like saying, "I'm building a CRM app but cannot use DI because DI is not built for customer relations management".

So yes, if you're already using DI in the rest of your application, IMO it would be wrong to not use it for the services handling localization.

这篇关于使用DI框架进行本地化-好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆