亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

ASP.NET?Core?MVC控制器請求依賴注入

 更新時間:2022年04月14日 15:17:58   作者:Ruby_Lu  
這篇文章介紹了ASP.NET?Core?MVC控制器請求依賴注入的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

ASP.NET Core MVC 控制器應(yīng)通過構(gòu)造函數(shù)明確地請求它們地依賴關(guān)系,在某些情況下,單個控制器地操作可能需要一個服務(wù),在控制器級別上的請求可能沒有意義。在這種情況下,也可以將服務(wù)作為  Action 的參數(shù)。

依賴注入是一種如 Dependency Inversion Principle 所示的技術(shù),允許應(yīng)用程序松散耦合的模塊組成。

1.構(gòu)造函數(shù)注入

ASP.NET Core 內(nèi)置的基于構(gòu)造函數(shù)的依賴注入支持擴展到 MVC 控制器。通過只添加一個服務(wù)類型作為構(gòu)造函數(shù)參數(shù)到控制器中,ASP.NET Core 將會嘗試使用內(nèi)置服務(wù)容器解析這個類型。服務(wù)通常(但不總是)使用接口定義。例如,如果應(yīng)用程序定義一個檢索時間的服務(wù),然后依賴注入而不是硬編碼:

定義接口和實現(xiàn):

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

在 ConfigureServices 中注冊服務(wù)到容器:

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 內(nèi)置的依賴注入支持用于請求服務(wù)的類型只能有一個構(gòu)造函數(shù),如果多于一個會報異常。使用第三方實現(xiàn)替換默認依賴注入,可以實現(xiàn)支持多個構(gòu)造函數(shù)。

2.使用 FromServices 操作注入

有時,不需要在控制器為多個操作提供服務(wù)。在這種情況下,將服務(wù)注入到操作方法的參數(shù)是有意義的。通過 [FromServices] 標記參數(shù)來實現(xiàn):

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

3.在控制器中訪問設(shè)置

在控制器中訪問應(yīng)用程序設(shè)置或者配置設(shè)置時常見的模式。此訪問應(yīng)當使用在 Configuration 中描述的訪問模式。通常不應(yīng)從控制器中使用依賴注入直接請求設(shè)置,更好的方式是請求 IOptions<T> 實例,T是你需要的配置類型。例如:

創(chuàng)建選項類:

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": "*"
}

配置應(yīng)用程序使用選項模型,在 ConfigureServices 中添加配置類到服務(wù)容器:

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)
                ;

            //配置環(huán)境變量
            //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 讀取設(shè)置,也可以在代碼中添加設(shè)置。

一旦指定了請類型的配置對象 AppSettingOptions,并將其添加到服務(wù)容器,就可以在控制器或操作方法通過請求 IOptions<AppSettingOptions>  的實例獲取它:

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

遵循選項模式允許將設(shè)置和配置彼此分離,并且確??刂破髯裱P(guān)注點分離,因為不需要知道如何在哪里找到設(shè)置信息。由于控制器類中沒有靜態(tài)附著或者直接實例化設(shè)置類,因此使得控制器更容易使用單元測試。

到此這篇關(guān)于ASP.NET Core MVC控制器請求依賴注入的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論