我有一个ASP.NET核心类库,它依赖于引用dll的项目中的依赖项注入。但是当我尝试获取服务时,服务始终为空。
这是我到目前为止唯一可行的设计,因为我想我不能直接在类库中设置依赖服务。
班级图书馆:
@include "join"
{
n=split($0, a, " ")
s=join(a, 1, n-1)
b[$NF s]=$0
}
END{
n=asorti(b,c);
for(j=1;j<=n;j++) print b[c[j]]
}
在引用类库的项目中启动:
public interface IHtmlResourceLocalizer
{
string Get(string cultureCode, string name);
string Get(CultureInfo culture, string name);
}
public class HtmlResourceLocalizer : IHtmlResourceLocalizer
{
private readonly IHostingEnvironment _env;
private readonly IHttpContextAccessor _context;
public HtmlResourceLocalizer(IHostingEnvironment env, IHttpContextAccessor context)
{
_env = env;
_context = context;
}
public string Get(string cultureCode, string name) { return Get(new CultureInfo(cultureCode), name); }
public string Get(CultureInfo culture, string name)
{
string result = string.Empty, filename = name + "." + culture.Parent.Name + ".cshtml";
string path = Path.Combine(this.Env.ContentRootPath, "Views", "Resources", filename);
if (File.Exists(path))
{
IRazorViewEngine engine = _context.HttpContext.Features.Get<IRazorViewEngine>();
ITempDataProvider temp = _context.HttpContext.Features.Get<ITempDataProvider>();
ViewRenderUtility util = new ViewRenderUtility(engine, temp, _context.HttpContext.RequestServices);
result = util.ViewToString(filename, null).Result;
}
else
{
throw new FileNotFoundException("Could not find file \"" + path + "\"");
}
return result;
}
public IHostingEnvironment Env { get { return _env; } }
}
查看:
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddSingleton<IHtmlResourceLocalizer, HtmlResourceLocalizer>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IRazorViewEngine, RazorViewEngine>();
services.AddSingleton<AppHelper>();
services.AddMvc()
.AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
}