我正在使用PO文件本地化ASP.NET MVC 5应用程序。
我创建了一个HTTP模块来交叉类型为html,javascript等的响应:
public class I18NModule : IHttpModule {
private Regex _types;
public I18NModule() {
_types = new Regex(@"^(?:(?:(?:text|application)/(?:plain|html|xml|javascript|x-javascript|json|x-json))(?:\s*;.*)?)$");
} // I18NModule
public void Init(HttpApplication application) {
application.ReleaseRequestState += OnReleaseRequestState;
} // Init
public void Dispose() {
} // Dispose
private void OnReleaseRequestState(Object sender, EventArgs e) {
HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
if (_types != null && _types.Match(context.Response.ContentType).Success)
context.Response.Filter = new I18NFilter(context, context.Response.Filter, _service);
} // Handle
} // I18NModule
然后我有一个I18NFilter如下:
public class I18NFilter : MemoryStream {
private II18NNuggetService _service;
protected HttpContextBase _context;
private MemoryStream _buffer = new MemoryStream();
protected Stream _output;
public I18NFilter(HttpContextBase context, Stream output, II18NNuggetService service) {
_context = context;
_output = output;
_service = service;
} // I18NFilter
public override void Write(Byte[] buffer, Int32 offset, Int32 count) {
_buffer.Write(buffer, offset, count);
} // Write
public override void Flush() {
Encoding encoding = _context.Response.ContentEncoding;
Byte[] buffer = _buffer.GetBuffer();
String entity = encoding.GetString(buffer, 0, (Int32)_buffer.Length);
_buffer.Dispose();
_buffer = null;
buffer = null;
*USE SERVICE TO LOAD PO FILE AND PROCESS IT*
buffer = encoding.GetBytes(entity);
encoding = null;
Int32 count = buffer.Length;
_output.Write(buffer, 0, count);
_output.Flush();
} // Flush
} // I18NFilter
当我与响应相交时,我查找字符串为[[[some text]]]。 "一些文字"将是我在PO文件中寻找当前线程语言的关键。
所以我需要为当前语言加载PO文件,处理它,并找到需要翻译的字符串。
我的问题是性能......我应该在静态类中加载整个文件吗?
我应该在每个请求中加载文件并使用CacheDependency吗?
我该怎么做?
答案 0 :(得分:1)
由于这是一个HTTP应用程序,我会利用HttpRuntime.Cache。以下是如何使用它来最小化性能成本的示例:
public override void Flush() {
...
var fileContents = GetLanguageFileContents();
...
}
private string GetLanguageFileContents(string languageName) {
if (HttpRuntime.Cache[languageName] != null)
{
//Just pull it from memory!
return (string)HttpRuntime.Cache[languageName];
}
else
{
//Take the IO hit :(
var fileContents = ReadFileFromDiskOrDatabase();
//Store the data in memory to avoid future IO hits :)
HttpRuntime.Cache[languageName] = fileContents;
return fileContents;
}
}