Autofac 可以将依赖项注入布局视图文件吗? [英] Can Autofac inject dependencies into layout view files?

查看:35
本文介绍了Autofac 可以将依赖项注入布局视图文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将依赖项注入共享布局视图页面,以避免在使用该布局的每个视图中都执行此操作.

I'm trying to inject a dependency into the shared layout view page to avoid having to do it in every view that uses the layout.

我已经按照 wiki 中的 指南 将依赖项注入到视图中,但是属性始终为空.

I've followed the guidance in the wiki for injecting dependencies into views, but the property is always null.

Autofac 可以将属性注入作为布局文件的自定义视图页面吗?

Can Autofac inject properties into a custom view page that is a layout file?

这是我的设置.自定义视图页面

Here's my setup. CustomViewPage

namespace MyApp
{
    using System.Web.Mvc;

    public abstract class CustomViewPage : WebViewPage
    {
        public IHelper Helper { get; set; }
    }
}

~/Views/Shared/_Layout.cshtml

~/Views/Shared/_Layout.cshtml

@inherits MyApp.CustomViewPage
<!DOCTYPE html>
<html>
...
@if(this.Helper.HasFoo()){@Html.ActionLink("Bar")}

全球注册...

builder.RegisterType<Helper>().AsImplementedInterfaces();
builder.RegisterModelBinderProvider();
builder.RegisterFilterProvider();
builder.RegisterModule(new AutofacWebTypesModule());
builder.RegisterSource(new ViewRegistrationSource());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

使用布局的子"视图不是从 CustomViewPage 派生的.

The "child" views that use the layout do NOT derive from the CustomViewPage.

推荐答案

大多数解决方案只是对 DependencyResolver.Current.GetService 调用进行包装,因此直接从布局中调用它可能更容易:

Most of solutions will be just a wrapper around DependencyResolver.Current.GetService call, so it might be easier to call it directly from layout:

@{
    var helper = DependencyResolver.Current.GetService<IHelper>();
}
...
@if (helper.HasFoo()) { @Html.ActionLink("Bar") }
...

这种方式也有助于使页面模型更具 SRP,因为可以避免混合服务例程/模型和业务模型.

Also this way helps to make page model more SRP, because can avoid mixing service routines/models and business ones.

这篇关于Autofac 可以将依赖项注入布局视图文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆