在我的布局视图中,我将一些缓存的数据从服务注入到布局视图中,如下所示;
<script type="text/javascript">
@(Html.Raw(EngineContext.Current.Resolve<IStringService>().GetStringsJson()));
</script>
它以json格式注入缓存的字符串。它确实有效,但我不得不使用Service Locator,它被认为是反模式。 这里有什么更好的解决方案?
谢谢,
答案 0 :(得分:0)
为了解决这个问题,我使用了全局actionfilter并将数据传递给viewbag中的视图。这是代码;
View getView(int i, View view, ViewGroup viewGroup)
注册依赖项(Autofac)
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public sealed class GlobalValuesActionFilter : ActionFilterAttribute
{
private readonly ICacheService _cacheService;
public GlobalValuesActionFilter(ICacheService cacheService)
{
this._cacheService = cacheService;
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.Controller.ViewBag.UIStrings = _cacheService.GetUIStrings();
}
}
并在视图中添加以下行;
builder.Register(c => new GlobalValuesActionFilter(c.Resolve<ICacheService>()))
.AsActionFilterFor<Controller>().InstancePerRequest();