Guga Todua
Guga Todua

Reputation: 522

.Resx file is empty when using it in .cs file

I am trying to read data from .resx file. It works fine in views, but having trouble when using it in .cs.

I am getting this runtime error:

Object reference not set to an instance of an object

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;
  });

I have SharedResources.ka.resx and SharedResources.en.resx files. How do I get data from these two files in SharedLocalizer instance of MailComposer.cs?

Upvotes: 0

Views: 40

Answers (1)

Nan Yu
Nan Yu

Reputation: 27588

Solution 1 :

Inject SharedResources in MailComposer.cs :

IStringLocalizer<SharedResource> SharedLocalizer;

public MailComposer(IStringLocalizer<SharedResource> _SharedLocalizer)
{
    SharedLocalizer = _SharedLocalizer;
}

Add below line in Startup.cs :

services.AddScoped<MailComposer>();

Inject MailComposer in the place where you want to call the SendActivityCreated function :

private readonly MailComposer _mailComposer;
public  HomeController(MailComposer mailComposer){

    _mailComposer = mailComposer;
}

And use like :

_mailComposer.SendActivityCreated(entity);

Solution 2 :

Inject SharedResources in MailComposer.cs :

IStringLocalizer<SharedResource> SharedLocalizer;

public MailComposer(IStringLocalizer<SharedResource> _SharedLocalizer)
{
    SharedLocalizer = _SharedLocalizer;
}

Inject IStringLocalizer<SharedResource> in the place where you want to call the SendActivityCreated function :

private readonly IStringLocalizer<SharedResource> _localizer;
public  HomeController(IStringLocalizer<SharedResource> localizer){

    _localizer = localizer;
}

And use like :

MailComposer a = new MailComposer(_localizer);
a.SendActivityCreated(entity);

Upvotes: 1

Related Questions