问题
I have a "Class Library" project with some "ViewComponents" on it and I already made them work on my "MVC 6 Web app" (thanks to this question) but now I'm trying to add language resources (localization) to my "ViewComponents". Any suggestion on how this should be done?.
I already added the necesary lines to the startup file on my "MVC 6 Web app":
startup.cs
[...]
services.AddMvc()
.AddViewLocalization(options => options.ResourcesPath = "Resources");
[...]
app.UseRequestLocalization(new RequestCulture(new CultureInfo("es-MX")));
Also I added the dependencies on my "Class Library" Views:
Views/Shared/Components/Header/foo.cshtml
@using Microsoft.AspNet.Mvc.Localization
@inject IViewLocalizer LocString
<h1>@LocString["HelloWorld"]</h1>
and created the Resource folder and file in my "Class Library" project:
-Resources
-Views.Shared.Components.Header.foo.cshtml.resx
but all I get is the name of the key "HelloWorld" instead of the localized resource "Hola mundo"
In short Am I missing something? Does anyone knows a way to use localized resources in "view components" from a "class library" on a "mvc 6 web app"
Notes:
I'm using mvc 6 RC1
Resources from other views that are not ViewComponents are working fine.
Thank you!
回答1:
The problem was that I didn't know the name of the resource file the compiler was looking for when accessing from a view component, so following this thread I used the IStringLocalizerFactory directly:
public class HeaderViewComponent : ViewComponent
{
private string viewName;
private readonly IStringLocalizer _localizer;
public HeaderViewComponent(IStringLocalizerFactory localizedFactory)
{
_localizer = localizedFactory.Create("name.of.your.resource.file", "Namespace");
}
public IViewComponentResult Invoke()
{
[...]
ViewBag.StringLocalizer = _localizer;
return View("name", model);
}
}
The second parameter of "Create" is the namespace of your "class library"
Then in my Invoke function I added the _localizer to the ViewBag to use it on the view (since I havent found a way to inject the IViewLocalizer using the localizedFactory I just created).
Also I added this to my "class library" project.json:
"resource": [ "Views/**", "Resources/**" ]
Hope it helps others looking for a solution to use resources on a class library
来源:https://stackoverflow.com/questions/34890555/asp-net-5-localization-using-view-components-in-a-separate-assembly