zoukankan      html  css  js  c++  java
  • 初识依赖注入

    微软在.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>()
  • 相关阅读:
    新购服务器流程
    nginx代理证书使用方法
    一键部署lnmp脚本
    mysql主从库配置读写分离以及备份
    Linux入门教程(更新完毕)
    Git 工作流程
    Git远程操作
    常用Git命令
    js数组去重
    Sublime Text设置快捷键让html文件在浏览器打开
  • 原文地址:https://www.cnblogs.com/NCoreCoder/p/9156814.html
Copyright © 2011-2022 走看看