Mak*_*sev 4 c# dependency-injection html-sanitizing asp.net-core
当我使用HtmlSanitizer而不使用 DI 时,效果很好。
不带 DI 的 HtmlSanitizer:
但是当我想HtmlSanitizer
使用 DI 时。
我添加到 Startup.cs 文件:
services.AddSingleton<IHtmlSanitizer, HtmlSanitizer>();
Run Code Online (Sandbox Code Playgroud)我使用存储库的构造函数来获取 的实例,IHtmlSanitizer
但在注入的HtmlSanitizer
实例中,AllowedTags
、 和AllowAttributes
为空。
带 DI 的 HtmlSanitizer:
如何HtmlSanitizer
使用 DI 获取填充属性?
.Net框架依赖注入试图注入可选的构造函数参数
public HtmlSanitizer(IEnumerable<string> allowedTags = null, IEnumerable<string> allowedSchemes = null,
IEnumerable<string> allowedAttributes = null, IEnumerable<string> uriAttributes = null, IEnumerable<string> allowedCssProperties = null, IEnumerable<string> allowedCssClasses = null)
{
AllowedTags = new HashSet<string>(allowedTags ?? DefaultAllowedTags, StringComparer.OrdinalIgnoreCase);
AllowedSchemes = new HashSet<string>(allowedSchemes ?? DefaultAllowedSchemes, StringComparer.OrdinalIgnoreCase);
AllowedAttributes = new HashSet<string>(allowedAttributes ?? DefaultAllowedAttributes, StringComparer.OrdinalIgnoreCase);
UriAttributes = new HashSet<string>(uriAttributes ?? DefaultUriAttributes, StringComparer.OrdinalIgnoreCase);
AllowedCssProperties = new HashSet<string>(allowedCssProperties ?? DefaultAllowedCssProperties, StringComparer.OrdinalIgnoreCase);
AllowedAtRules = new HashSet<CssRuleType>(DefaultAllowedAtRules);
AllowedCssClasses = allowedCssClasses != null ? new HashSet<string>(allowedCssClasses) : null;
}
Run Code Online (Sandbox Code Playgroud)
这会导致 DI 容器使用空集合来初始化目标HtmlSanitizer
类。
在这种情况下,在注册类时使用工厂委托并调用构造函数(就像不使用 DI 时所做的那样)
services.AddSingleton<IHtmlSanitizer>(_ => new HtmlSanitizer());
Run Code Online (Sandbox Code Playgroud)
或者简单地创建实例并将其注册到 DI 容器
IHtmlSanitizer sanitizer = new HtmlSanitizer();
services.AddSingleton<IHtmlSanitizer>(sanitizer);
Run Code Online (Sandbox Code Playgroud)