来吧学学.Net Core之项目文件简介及配置文件与IOC的使用

序言

在当前编程语言蓬勃发展与竞争的时期,对于咱们.net从业者来讲,.Net Core是风头正紧,势不可挡的.芸芸口水之中,不学习使用Core,你的圈内处境或许会渐渐的被边缘化.因此咱们仍是抽出一点点时间学学.net core吧.前端

那VS Code 能够编写,也能够调试Core本人也尝试啦下,可是感受扯淡的有点多,仍是使用宇宙第一开发工具VS2017吧.web

因为本篇是core的开篇,因此就稍微啰嗦一点,从建立web项目开始,先说项目文件,再来讲一说配置文件与IOC使用.编程

建立web项目及项目文件简介

关于web项目的建立,若是你建立不出来,自生自灭吧.点击右上角的x,拜拜.json

从上往下说这个目录结构windows

一、launchSettings.json 启动配置文件,文件默认内容以下.mvc

{
  "iisSettings": {      //使用IIS Express启动
    "windowsAuthentication": false,  //是否启用windows身份验证  
    "anonymousAuthentication": true,  //是否启用匿名身份验证
    "iisExpress": {
      "applicationUrl": "http://localhost:57566/",   //访问域名,端口
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"  //环境变量,默认为开发环境(Development),预发布环境(Staging),生产环境(Production)
      }
    },
    "WebApplication1": {          //选择本地自宿主启动,详见Program.cs文件。删除该节点也将致使Visual Studio启动选项缺失
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:57567"    //本地自宿主端口
    }
  }
}

在vs的设计视图中也能够编辑,以下图,本身扣索下.app

二、wwwroot和bower.json 静态资源文件夹与引入静态资源库包版本配置文件,本身打开看下编程语言

三、依赖项,这个里面有4种吧,一种是bower前端资源库,Nuget第三方,SDK,项目自己ide

四、Controllers,Views,这个不用介绍吧,mvc的2主.工具

五、appsettings.json :应用配置文件,相似于.net framework中的web.config文件

六、bundleconfig.json:打包压缩配置文件

7、Program.cs:里面包含一个静态Main文件,为程序运行的入口点

8、Startup.cs:这个默认为程序启动的默认类.

这里的配置文件与2个入口类文件是万物的根基,灵活多变,其中用咱们值得学习了解的东西不少,这一章我不作阐述,后续章节再来补习功课,见谅,谨记.

.Net Core读取配置文件

这个是我第一次入手学习core时候的疑问,我先是按照.Net Framework的方法来读取配置文件,发现Core中根本没有System.Configuration.dll.那怎么读取配置文件呢?

那么若是要读取配置文件中的数据,首先要加载Microsoft.Extensions.Configuration这个类库.

首先看下个人默认配置文件,appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }  
}

读取他的第一种方式

        /// <summary>
        /// 获取配置节点对象
        /// </summary>   
        public static T GetSetting<T>(string key, string fileName = "appsettings.json") where T : class, new()
        {
            IConfiguration config = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .Add(new JsonConfigurationSource { Path = fileName, Optional = false, ReloadOnChange = true })
               .Build();
            var appconfig = new ServiceCollection()
                .AddOptions()
                .Configure<T>(config.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
            return appconfig;
        }
    public class Logging
    {
        public bool IncludeScopes { get; set; }
        public LogLevel LogLevel { get; set; }
    }
    public class LogLevel
    {
        public String Default { get; set; }
    }
var result =GetSetting<Logging>("Logging");

这样便可,读取到配置文件的内容,并填充配置文件对应的对象Logging.

若是你有自定义的节点,以下

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "Cad": {
    "a": false,
    "b": "18512312"    
  }  
}

与上面同样,首先定义对应的对象

  public class Cad
    {
        public bool a { get; set; }
        public string b { get; set; }
    }
var result = GetSetting<Cad>("Cad");

有啦上面的方法非常简单,还有一种状况是你想有本身的配置文件myconfig.json,那也很简单,把上述方法的默认文件名改成myconfig.json便可!

除啦这个方法能够获取配置文件外,core在mvc中还有另外获取配置文件的方法,以下.

        IOptions<Cad> cadConfig;
        public HomeController(IOptions<Cad> config)
        {
            cadConfig = config;
        }

        public IActionResult Index()
        {
            try
            {
                var result = cadConfig.Value;
                return View(result);
            }
            catch (Exception ex)
            {
                return View(ex);
            }
        }

就这样,用法也很简单.

可是若是配置文件中有的配置项须要你动态修改,怎么办呢,用下面的方法试试.

        /// <summary>
        /// 设置并获取配置节点对象
        /// </summary>  
        public static T SetConfig<T>(string key, Action<T> action, string fileName = "appsettings.json") where T : class, new()
        {
            IConfiguration config = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile(fileName, optional: true, reloadOnChange: true)
               .Build();
            var appconfig = new ServiceCollection()
                .AddOptions()
                .Configure<T>(config.GetSection(key))
                .Configure<T>(action)
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
            return appconfig;
        }
  var c =SetConfig<Cad>("Cad", (p => p.b = "123"));

ok啦,本身试试吧,对配置文件的读取,我这里目前只作到这里,后续有新的好方法再来分享.

.Net Core中运用IOC

固然在.net framework下可以作依赖注入的第三方类库不少,咱们对此也了然于心,可是在core中无须引入第三放类库便可作到.

    public interface IAmount
    {
        string GetMyBanlance();
        string GetMyAccountNo();
    }

    public class AmountImp: IAmount
    {
        public string GetMyBanlance()
        {
            return "88.88";
        }
        public string GetMyAccountNo()
        {
            return "CN0000000001";
        }
    }

上面一个接口,一个实现,下面咱们在Startup的ConfigureServices中把接口的具体实现注册到ioc容器中.

 public class Startup
    {       
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<IAmount, AmountImp>();
            // Add framework services.
            services.AddMvc();
        }
    }
    public class HomeController : Controller
    {
        IAmount amount;
        public HomeController(IAmount _amount)
        {
            amount = _amount;
        }

        public IActionResult Index()
        {
            try
            {
                var result = amount.GetMyAccountNo(); //结果为: "CN0000000001"
                return View();
            }
            catch (Exception ex)
            {
                return View(ex);
            }
        }
}

这里呢,我只作一个简单的示例,以供咱们熟悉了解core,后续章节,若是运用的到会深刻.

总结

入手.net core仍是须要有不少新的认识点学习的,不是一两篇博文能够涵盖的,咱们本身须要多总结思考学习.

这里我把一些的点,贴出来,但愿对想入手core的同窗有所帮助.若有志同道合者,欢迎加左上方群,一块儿学习进步.

相关文章
相关标签/搜索