Search code examples
aspnetboilerplate

How to get / inject ILocalizationContext inside service or controller


I'd like to know how to get ILocalizationContext inside the service or the controller. For example, I would like to get the DisplayName of the permission but it requires "ILocalizationContext": DisplayName.Localize(ILocalizationContext). I tried injection, it doesn't work...

I tried multiple ways to inject it, constructor, using... I can see something similar inside "PermissionCheckerExtensions" :

var iocManager = (permissionChecker as IIocManagerAccessor).IocManager;
        using (var localizationContext = iocManager.ResolveAsDisposable<ILocalizationContext>())
        {
            using (var permissionManager = iocManager.ResolveAsDisposable<IPermissionManager>())
            {
                return permissionNames.Select(permissionName =>
                {
                    var permission = permissionManager.Object.GetPermissionOrNull(permissionName);
                    return permission?.DisplayName == null
                        ? permissionName
                        : permission.DisplayName.Localize(localizationContext.Object);
                }).ToArray();
            }
        }

Edit:

The problem was from myself... You can just inject it with the controller and it should work.


Solution

  • I've tried inside PostInitialize with Resolve

    • You should not localize in PostInitialize. There is no user to localize for.
    • It should work inside AppService and Controller.

    Make sure you:

    • inject where there actually is a localization context.
    • await async methods.