ASP.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

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

如果你觉得本文对你有帮助,请点击“推荐”,谢谢。

时间: 2024-08-25 17:22:23

ASP.NET Core开发-获取所有注入(DI)服务的相关文章

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 in

ASP.NET Core中的依赖注入(2):依赖注入(DI)

参考页面: http://www.yuanjiaocheng.net/ASPNET-CORE/project-layout.html http://www.yuanjiaocheng.net/ASPNET-CORE/projectjson.html http://www.yuanjiaocheng.net/ASPNET-CORE/core-configuration.html http://www.yuanjiaocheng.net/ASPNET-CORE/core-middleware.htm

ASP.NET Core中的依赖注入(5): ServiceProvider实现揭秘 【解读ServiceCallSite 】

通过上一篇的介绍我们应该对实现在ServiceProvider的总体设计有了一个大致的了解,但是我们刻意回避一个重要的话题,即服务实例最终究竟是采用何种方式提供出来的.ServiceProvider最终采用何种方式提供我们所需的服务实例取决于最终选择了怎样的ServiceCallSite,而服务注册是采用的ServiceDescriptor有决定了ServiceCallSite类型的选择.我们将众多不同类型的ServiceCallSite大体分成两组,一组用来创建最终的服务实例,另一类则与生命周

ASP.NET Core中的依赖注入(5): ServiceProvider实现揭秘 【总体设计 】

本系列前面的文章我们主要以编程的角度对ASP.NET Core的依赖注入系统进行了详细的介绍,如果读者朋友们对这些内容具有深刻的理解,我相信你们已经可以正确是使用这些与依赖注入相关的API了.如果你还对这个依赖注入系统底层的实现原理具有好奇心,可以继续阅读这一节的内容. 目录一.ServiceCallSite 二.Service 三.ServiceEntry 四.ServiceTable 五.ServiceProvider 作为DI容器的体现,ServiceProvider是ASP.NET Co

ASP.NET Core开发-读取配置文件Configuration

ASP.NET Core 是如何读取配置文件,今天我们来学习. ASP.NET Core的配置系统已经和之前版本的ASP.NET有所不同了,之前是依赖于System.Configuration和XML配置文件web.config. 新的配置系统支持多种格式的配置文件. 下面我们来以json 格式的配置文件正式开始学习. 我们新建一个ASP.NET Core Web 应用程序,选择无身份验证. 读取配置文件 在项目目录下有个 appsettings.json ,我们先来操作这个文件. 在appse

ASP.NET Core中的依赖注入(5):ServicePrvider实现揭秘【补充漏掉的细节】

到目前为止,我们定义的ServiceProvider已经实现了基本的服务提供和回收功能,但是依然漏掉了一些必需的细节特性.这些特性包括如何针对IServiceProvider接口提供一个ServiceProvider对象,何创建ServiceScope,以及如何提供一个服务实例的集合. 一.提供一个ServiceProvider对象 我们知道当将服务类型指定为IServiceProvider接口并调用ServiceProvider的GetService方法是,ServiceProvider对象本

ASP.NET Core 开发-Logging 使用NLog 写日志文件

ASP.NET Core 开发-Logging 使用NLog 写日志文件. NLog 可以适用于 .NET Core 和 ASP.NET Core . ASP.NET Core已经内置了日志支持,可以轻松输出到控制台. 学习Logging 组件的相关使用,使用NLog 将日志写入到文件记录. Logging 使用 新建一个 ASP.NET Core 项目,为了方便,我选择Web 应用程序,改身份验证 改为 不进行身份验证. 新建好以后,会自动引用好对应的 类库.这样我们就可以直接使用 Logge

ASP.NET Core开发-后台任务利器Hangfire使用

ASP.NET Core开发系列之后台任务利器Hangfire 使用. Hangfire 是一款强大的.NET开源后台任务利器,无需Windows服务/任务计划程序. 可以使用于ASP.NET 应用也可以使用于控制台.Hangfire 只需简单几句代码即可创建新的不同种类的任务. 目前 Hangfire 已经支持.NET Core ,现在就给大家讲解下在ASP.NET Core 里的使用. Hangfire GitHub:https://github.com/HangfireIO/Hangfir

ASP.NET Core 开发-中间件(Middleware)

参考页面: http://www.yuanjiaocheng.net/ASPNET-CORE/core-razor-layout.html http://www.yuanjiaocheng.net/ASPNET-CORE/core-view-start.html http://www.yuanjiaocheng.net/ASPNET-CORE/core-import-view.html http://www.yuanjiaocheng.net/ASPNET-CORE/core-razor-tag