我正在尝试从.resx文件读取数据。它在视图中工作正常,但是在.cs中使用时遇到麻烦。
我遇到此运行时错误:
对象引用未设置为对象的实例
MailComposer.cs
IStringLocalizer<SharedResources> SharedLocalizer;
public void SendActivityCreated (Activity entity) {
var path = Path.Combine (environment.ContentRootPath, "wwwroot", "mail_templates", "activity_created", "index.html");
var template = File.ReadAllText (path);
template = template.Replace ("##ID##", entity.ID.ToString ());
var x = SharedLocalizer["NewActivity"]; // Getting "Object reference not set to an instance of an object" here
var title = $"Platform.Ge - {x} #{entity.ID}";
var responsibleEmail = template.Replace ("##USER##", entity.Responsible.Name);
emailSender.SendEmailAsync (entity.Responsible.Email, title, responsibleEmail);
}
Startup.cs
services.Configure<RequestLocalizationOptions> (opts => {
var supportedCultures = new [] {
new CultureInfo ("en"),
new CultureInfo ("ka"),
new CultureInfo ("ru")
};
opts.DefaultRequestCulture = new RequestCulture ("ka");
// Formatting numbers, dates, etc.
opts.SupportedCultures = supportedCultures;
// UI strings that we have localized.
opts.SupportedUICultures = supportedCultures;
});
我有SharedResources.ka.resx和SharedResources.en.resx文件。如何从MailComposer.cs的SharedLocalizer实例中的这两个文件中获取数据?
答案 0 :(得分:1)
解决方案1:
在SharedResources
中注入MailComposer.cs
:
IStringLocalizer<SharedResource> SharedLocalizer;
public MailComposer(IStringLocalizer<SharedResource> _SharedLocalizer)
{
SharedLocalizer = _SharedLocalizer;
}
在Startup.cs
中添加以下行:
services.AddScoped<MailComposer>();
在要调用MailComposer
函数的位置注入SendActivityCreated
:
private readonly MailComposer _mailComposer;
public HomeController(MailComposer mailComposer){
_mailComposer = mailComposer;
}
并像这样使用:
_mailComposer.SendActivityCreated(entity);
解决方案2:
在SharedResources
中注入MailComposer.cs
:
IStringLocalizer<SharedResource> SharedLocalizer;
public MailComposer(IStringLocalizer<SharedResource> _SharedLocalizer)
{
SharedLocalizer = _SharedLocalizer;
}
在要调用IStringLocalizer<SharedResource>
函数的位置注入SendActivityCreated
:
private readonly IStringLocalizer<SharedResource> _localizer;
public HomeController(IStringLocalizer<SharedResource> localizer){
_localizer = localizer;
}
并像这样使用:
MailComposer a = new MailComposer(_localizer);
a.SendActivityCreated(entity);