zoukankan      html  css  js  c++  java
  • asp.net Core 依赖注入常用获取服务的3种方法

    先看简单的demo代码:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading.Tasks;
    using WebApplication1.Models;
    
    namespace WebApplication1.Controllers
    {
        public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;
            private readonly IHostEnvironment _hostEnvironment;
            public HomeController(ILogger<HomeController> logger,IHostEnvironment hostEnvironment)
            {
                _logger = logger;
     _hostEnvironment = hostEnvironment; }
    public IActionResult Index([FromServices] IHostEnvironment hostEnvironment) { //1、通过构造函数注入,获取值 string path = _hostEnvironment.ContentRootPath; //2、通过方法的FromServices注入进来,获取值 string path2 = hostEnvironment.ContentRootPath; //通过GetRequiredService来检索服务 var hostEnvironment2 = HttpContext.RequestServices.GetRequiredService<IHostEnvironment>(); string path3= hostEnvironment2.ContentRootPath; return View(); } } }
     1、通过构造函数注入,获取值
     2、通过方法的FromServices注入进来,获取值
     3、通过GetRequiredService来检索服务
    
    

    作者:沐雪
    文章均系作者原创或翻译,如有错误不妥之处,欢迎各位批评指正。本文版权归作者和博客园共有,如需转载恳请注明。
    如果您觉得阅读这篇博客让你有所收获,请点击右下方【推荐】
    找一找教程网-随时随地学软件编程 http://www.zyiz.net/

  • 相关阅读:
    markdown基本语法
    每天一个Linux命令:pwd(3)
    每天一个Linux命令:cd(2)
    每天一个Linux命令:ls(1)
    每天一个Linux命令:man(0)
    maven命令行创建项目问题
    Regular Expression
    JS事件流
    canvas与svg区别
    js调试
  • 原文地址:https://www.cnblogs.com/puzi0315/p/14983163.html
Copyright © 2011-2022 走看看