NET Core開發-獲取所有注入(DI)服務


NET Core開發-獲取所有注入(DI)服務

獲取ASP.NET Core中所有注入(DI)服務,在ASP.NET Core中加入了Dependency Injection依賴注入。

我們在Controller,或者在ASP.NET Core程序中的其他地方使用注入的服務,如logging 等。

我們要怎樣獲取ASP.NET Core中所有注入(DI)服務呢,下面我們來一探究竟, 也可以來看看ASP.NET Core到底注入了哪些服務。

依賴注入簡單介紹:

依賴注入(Dependency injection , DI)是一種實現對象及其合作者或依賴項之間松散耦合的技術。將類用來執行其操作的這些對象以某種方式提供給該類,而不是直接實例化合作者或使用靜態引用。

 

我們新建一個ASP.NET Core 空應用程序。

然后Startup 中定義一個變量 private IServiceCollection _services;

復制代碼
    public class Startup
    {
        private IServiceCollection _services;
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            _services = services;
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            var _logger = loggerFactory.CreateLogger("Services");
            _logger.LogInformation($"Total Services Registered: {_services.Count}");
            foreach (var service in _services)
            {
                _logger.LogInformation($"Service: {service.ServiceType.FullName}\n      Lifetime: {service.Lifetime}\n      Instance: {service.ImplementationType?.FullName}");
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }
復制代碼

在 Configure 中使用Logger打印出來。

執行程序,可以看到,默認有14個服務。

 

然后我們也可以將這些服務在網頁中展示出來。

我們在 Configure 中加入如下代碼:

復制代碼
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            var _logger = loggerFactory.CreateLogger("Services");
            _logger.LogInformation($"Total Services Registered: {_services.Count}");
            foreach (var service in _services)
            {
                _logger.LogInformation($"Service: {service.ServiceType.FullName}\n      Lifetime: {service.Lifetime}\n      Instance: {service.ImplementationType?.FullName}");
            }

            if (env.IsDevelopment())
            {
                app.Map("/allservices", builder => builder.Run(async context =>
                {
                    context.Response.ContentType = "text/html; charset=utf-8";
                    await context.Response.WriteAsync($"<h1>所有服務{_services.Count}個</h1><table><thead><tr><th>類型</th><th>生命周期</th><th>Instance</th></tr></thead><tbody>");
                    foreach (var svc in _services)
                    {
                        await context.Response.WriteAsync("<tr>");
                        await context.Response.WriteAsync($"<td>{svc.ServiceType.FullName}</td>");
                        await context.Response.WriteAsync($"<td>{svc.Lifetime}</td>");
                        await context.Response.WriteAsync($"<td>{svc.ImplementationType?.FullName}</td>");
                        await context.Response.WriteAsync("</tr>");
                    }
                    await context.Response.WriteAsync("</tbody></table>");
                }));
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
復制代碼

然后我們使用自宿主的方式執行,在地址欄輸入 http://localhost:5000/allservices

同樣可以看到14個服務,這里我將/allservices 放在 Development 環境下,只有在程序調試時才能看到,運行是不行的。

 

我們在項目添加 Microsoft.AspNetCore.Mvc.Core 的引用 。

然后在 ConfigureServices 中加入

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore();//添加MvcCore
            _services = services;
        }

 

我們就可以看到MvcCore 里多加注入的服務

http://localhost:5000/allservices

可以看到增加很多的服務。我們也可以添加其他的,然后查看注入了哪些服務。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM