初识依赖注入

微软在.net core下面,广泛应用依赖注入,框架是开源的,链接地址:

https://github.com/aspnet/DependencyInjection

新建一个空asp.net core的webapi

默认Startup.cs

内容如下

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        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.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }

启动的过程,先是注入了构造方法,传入配置,

先后注入方法ConfigureServices、Configure

依赖注入是把调用的地方,从类操作改为接口操作,由容器统一提供

依赖注入的核心是IServiceCollection.Add

根据使用的生命周期不同,又分为

Transient: 每一次GetService都会创建一个新的实例

Scoped:  在同一个Scope内只初始化一个实例 ,可以理解为( 每一个request级别只创建一个实例,同一个http request会在一个 scope内)

Singleton :整个应用程序生命周期以内只创建一个实例

在这个基础上,又有一堆的延伸

我们自己根据这些,写点demo,看看运行结果

编写一个类

    public class TestIoc
    {
        public Guid Id { get; } = Guid.NewGuid();
    }

在Startup的ConfigureServices方法里添加依赖

services.AddTransient<TestIoc>();

我们创建默认asp.net core项目,不是有个控制器吗?改造一下他

        private TestIoc testIoc { get; }
        public ValuesController(TestIoc testIoc)
        {
            this.testIoc = testIoc;
        }

        // GET api/values
        [HttpGet]
        public Guid Get()
        {
            return testIoc.Id;
        }

我们运行一下,看结果

再刷新一下

内容每次都变了

我们有的时候,希望创建的实例,每次都一样

再修改一下

services.AddSingleton<TestIoc>()
原文地址:https://www.cnblogs.com/NCoreCoder/p/9156814.html