Can I use IStringLocalizer in a class which is not a Controller

Viewed 14496

I understand how to use the IStringLocalizer interface in a class which derives from Controller, for example as described here or here.

What would be the correct way to use IStringLocalizer in a class which does not derive from Controller?

I cannot find any examples addressing this question.

Is it always necessary to pass in an IStringLocalizer or IStringLocalizerFactory to the constructor?

Note.
I know that this is a fairly generic question (and Stack Overflow is for concrete programming questions). The background is that I make a localization tool for .NET projects. I am trying to figure out what changes my tool has to make to the source code to support localization in ASP.NET Core projects.

2 Answers

You can move the Shared resource Files (sharedResource.en-US.resx, sharedResource.ko-kr and etc ) to the Business layer library by creating a folder called "Resources" instead of on the Web/API project. But make sure that resource location relative path's value on the Startup should be empty.

services.AddLocalization(options => options.ResourcesPath = "");

Your SharedResouce.cs file looks like below.

namespace your.business.library.namespace.Resources
{
    public interface ISharedResource
    {
    }
    public class SharedResource : ISharedResource
    {
        private readonly IStringLocalizer _localizer;

        public SharedResource(IStringLocalizer<SharedResource> localizer)
        {
            _localizer = localizer;
        }

        public string this[string index]
        {
            get
            {
                return _localizer[index];
            }
        }
    }
}

define the filed to access the business class required.

private readonly IStringLocalizer<SharedResource> _localizer;

    public AppointmentBookingBL(IStringLocalizer<SharedResource> localizer)
    {
        _localizer = localizer;
    }

fetch the message from a resource like below

      public void ModifyBooking(BookingModel model)
        {
            ......... code here
            
                var message = _localizer["BOOKINGNOTAVAILABLE"];
               
            ..... code here
        }
Related