华域联盟 .Net ASP.NET Core MVC 依赖注入View与Controller

ASP.NET Core MVC 依赖注入View与Controller

一、ASP.NET Core MVC 之依赖注入 View

  ASP.NET Core 支持在试图中使用依赖注入。这将有助于提供视图专用的服务,比如本地化或者仅用于填充视图元素的数据。应尽量保持控制器和视图之间的关注点分离。视图所显示的大部分数据应该从控制器传入。

  使用 @inject 指令将服务注入到视图,语法 @inject <type> <name> 

例如:

@model MVCTest.Models.Operation
@using MVCTest.Services
@inject BaseInfoServices BaseInfoServices

@{
    ViewData["Title"] = "Create";
}
<ul>
    @foreach (var city in BaseInfoServices.GetCities())
    {
    <li>@city</li>
    }
</ul>

    public class BaseInfoServices
    {
        public List<string> GetCities()
        {
            return new List<string>();
        }
    }

  需要提前在 ConfigureServices 中配置,将该服务加入到容器。

 1.填充查找数据

  视图注入有助于填充 UI 元素,例如下拉框列表。比如一个包括性别,州以及其他用户资料的表单。如果通过标准的 MVC 方式渲染这个表单,则需要控制器为每一组选项都请求数据访问服务,然后将每一组绑定的选项填充到模型或ViewBag中。

  另一种则是直接将服务注入到视图中以获取这些选项数据。这种方法将控制器代码量减少到最少,把构造视图元素的逻辑移到视图本身去。控制器 Action 只需把用户资料数据传个表单即可。

2.重写服务

  除了注入服务外,此技术还可用于重写页面上先前注入的服务。例如,替换默认的HTML Helper

@model MVCTest.Models.Operation
@using MVCTest.Services
@inject BaseInfoServices BaseInfoServices
@inject MyHtmlHelper Html


  在视图中使用 @Html 将会调用自定义的服务。

  如果想要扩展现有服务而不是替换,则只需在使用此技术的同时,让服务继承或者封装已有实现即可。

二、 ASP.NET Core MVC 之依赖注入 Controller

ASP.NET Core MVC 控制器应通过构造函数明确地请求它们地依赖关系,在某些情况下,单个控制器地操作可能需要一个服务,在控制器级别上的请求可能没有意义。在这种情况下,也可以将服务作为  Action 的参数。

  依赖注入是一种如 Dependency Inversion Principle 所示的技术,允许应用程序松散耦合的模块组成。

1.构造函数注入

  ASP.NET Core 内置的基于构造函数的依赖注入支持扩展到 MVC 控制器。通过只添加一个服务类型作为构造函数参数到控制器中,ASP.NET Core 将会尝试使用内置服务容器解析这个类型。服务通常(但不总是)使用接口定义。例如,如果应用程序定义一个检索时间的服务,然后依赖注入而不是硬编码:

定义接口和实现:

namespace MVCTest.Services
{
    public interface IDateTime
    {
        DateTime Now { get; }
    }
    public class SystemDateTime: IDateTime
    {
        public DateTime Now
        {
            get { return DateTime.Now; }
        }
    }
}

ConfigureServices 中注册服务到容器:

services.AddTransient<IDateTime, SystemDateTime>();


在控制其中使用:

    public class DateTimeController : Controller
    {
        private IDateTime _dateTime;
        public DateTimeController(IDateTime dateTime)
        {
            _dateTime = dateTime;
        }
        // GET: DateTime
        public ActionResult Index()
        {
            var serverTime = _dateTime.Now;
            if (serverTime.Hour < 12)
            {
                ViewData["Message"] = "Good Morning";
            }
            return View();
        }
}

  ASP.NET Core 内置的依赖注入支持用于请求服务的类型只能有一个构造函数,如果多于一个会报异常。使用第三方实现替换默认依赖注入,可以实现支持多个构造函数。

2.使用 FromServices 操作注入

  有时,不需要在控制器为多个操作提供服务。在这种情况下,将服务注入到操作方法的参数是有意义的。通过 [FromServices] 标记参数来实现:

  public ActionResult Index([FromServices] IDateTime _dateTime)
        {
            var serverTime = _dateTime.Now;
            if (serverTime.Hour < 12)
            {
                ViewData["Message"] = "Good Morning";
            }
            return View();
        }

 3.在控制器中访问设置

  在控制器中访问应用程序设置或者配置设置时常见的模式。此访问应当使用在 Configuration 中描述的访问模式。通常不应从控制器中使用依赖注入直接请求设置,更好的方式是请求 IOptions<T> 实例,T是你需要的配置类型。例如:

创建选项类:

public class AppSettingOptions
    {
        public DefaultConnec ConnectionStrings { get; set; }
        public string AllowedHosts { get; set; }
    }

    public class DefaultConnec
    {
        public string DefaultConnection { get; set; }
    }

appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=Test;Integrated Security=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  },
  "AllowedHosts": "*"
}

配置应用程序使用选项模型,在 ConfigureServices 中添加配置类到服务容器:

public Startup(IConfiguration configuration,IHostingEnvironment env)
        {
            //Configuration = configuration;
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json",optional:true,reloadOnChange:true)
                //.AddJsonFile($"appsettings.{env.EnvironmentName}.json",optional:true)
                ;

            //配置环境变量
            //builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            services.Configure<AppSettingOptions>(Configuration);
            //通过代码编写
            services.Configure<AppSettingOptions>(options=>
            {
                options.AllowedHosts = "test";
            });
        }

示例是从 appsettings.json 读取设置,也可以在代码中添加设置。

  一旦指定了请类型的配置对象 AppSettingOptions,并将其添加到服务容器,就可以在控制器或操作方法通过请求 IOptions<AppSettingOptions>  的实例获取它:

    public class HomeController : Controller
    {
        private readonly IOptions<AppSettingOptions> _options;
        public HomeController(IOptions<AppSettingOptions> options)
        {
            _options = options;
        }
}

  遵循选项模式允许将设置和配置彼此分离,并且确保控制器遵循关注点分离,因为不需要知道如何在哪里找到设置信息。由于控制器类中没有静态附着或者直接实例化设置类,因此使得控制器更容易使用单元测试。

到此这篇关于ASP.NET Core MVC 依赖注入View与Controller的文章就介绍到这了,更多相关ASP.NET Core MVC 依赖注入内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

您可能感兴趣的文章:

  • 理解ASP.NET Core 依赖注入(Dependency Injection)
  • ASP.NET Core实现自动依赖注入
  • 详解asp.net core 依赖注入
  • ASP.NET Core 过滤器中使用依赖注入知识点总结
  • ASP.NET Core依赖注入系列教程之控制反转(IoC)
  • ASP.NET Core 依赖注入详细

本文由 华域联盟 原创撰写:华域联盟 » ASP.NET Core MVC 依赖注入View与Controller

转载请保留出处和原文链接:https://www.cnhackhy.com/80338.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部