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

序言

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

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

由于本篇是core的开篇,所以就稍微啰嗦一点,从创建web项目开始,先说项目文件,再来说一说配置文件与IOC使用.

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

关于web项目的创建,如果你创建不出来,自生自灭吧.点击右上角的x,拜拜.

从上往下说这个目录结构

1、launchSettings.json 启动配置文件,文件默认内容如下.

{
  "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的设计视图中也可以编辑,如下图,自己扣索下.

2、wwwroot和bower.json 静态资源文件夹与引入静态资源库包版本配置文件,自己打开看下

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

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

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

6、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的同学有所帮助.如有志同道合者,欢迎加左上方群,一起学习进步.

posted @ 2017-06-27 11:27  张龙豪  阅读(6613)  评论(9编辑  收藏  举报