來吧學學.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的同窗有所幫助.若有志同道合者,歡迎加左上方羣,一塊兒學習進步.

相關文章
相關標籤/搜索