热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

【无标题】.Net6开发winform程序使用依赖注入学习通http://www.bdgxy.com/

文章来源:学习通http:www.bdgxy.com普学网http:www.boxinghulanban.cn智学网http:www.jaxp.net表格制作e

文章来源: 学习通http://www.bdgxy.com/

普学网http://www.boxinghulanban.cn/

智学网http://www.jaxp.net/

表格制作excel教程http://www.tpyjn.cn/

学习通http://www.tsgmyy.cn/


.net? Blazor webassembly 和 webAPI 内建支持依赖注入, Winform 和 Console 应用虽然不带有依赖注入功能, 但增加依赖注入也很简单.?

本文将示例如何为 WinForm 程序增加依赖注入特性, 实现通过DI容器获取Cofiguration 实例, 并读取appsettings.json文件.

安装依赖库, 有点多


  • Microsoft.Extensions.DependencyInjection 库, 依赖注入的类库
  • Microsoft.Extensions.Configuration 库, 包含IConfiguration接口 和 Configuration类
  • Microsoft.Extensions.Configuration.Json 库, 为 IConfiguration 增加了读取 Json 文件功能,
  • Microsoft.Extensions.Hosting 库,? 提供 Host 静态类,? 有能力从 appsettings.{env.EnvironmentName}.json 加载相应 env? 的设定值,? 并将设定值用于IConfiguration/ILoggerFactory中, 同时增加 Console/EventSourceLogger 等 logger. 仅适用于 Asp.Net core 和 Console 类应用
  • Microsoft.Extensions.Logging 库,? 包含 ILogger 和 ILoggerFactory 接口
  • Serilog.Extensions.Logging 库, 为DI 容器提供 AddSerilog() 方法.
  • Serilog.Sinks.File 库, 提供 Serilog rolling logger
  • Serilog.Sinks.Console 库, 增加 serilog console logger
  • Serilog.Settings.Configuration 库, 允许在 appsetting.json? 配置 Serilog, 顶层节点要求是 Serilog.?
  • Serilog.Enrichers.Thread 和 Serilog.Enrichers.Environment 库,? 为输出日志文本增加 Thread和 env 信息

补充库:


  • Microsoft.Extensions.Options.ConfigurationExtensions 库,? 为DI容器增加了从配置文件中实例化对象的能力, 即? serviceCollection.Configure(IConfiguration)
  • Microsoft.Extensions.Options 库,? 提供以强类型的方式读取configuration文件, 这是.Net中首选的读取configuration文件方式.

appsettings.json 配置文件

配置一个 ConnectionString, 另外配 serilog

{

“ConnectionStrings”: {
“oeeDb”: “Server=localhost\SQLEXPRESS01;Database=Oee;Trusted_Connection=True;”
},

“Serilog”: {
“Using”: [ “Serilog.Sinks.Console”, “Serilog.Sinks.File” ],
“MinimumLevel”: “Debug”,
“WriteTo”: [
{ “Name”: “Console” },
{
“Name”: “File”,
“Args”: { “path”: “Logs/serilog.txt” }
}
],
“Enrich”: [ “FromLogContext”, “WithMachineName”, “WithThreadId” ]
}
}

Program.cs , 增加DI容器


using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using Serilog;

namespace Collector
{
internal static class Program
{
///


/// The main entry point for the application.
///

[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
//未使用依赖注入的写法
//Application.Run(new FormMain());

//生成 DI 容器ServiceCollection services = new ServiceCollection();ConfigureServices(services); //注册各种服务类//先用DI容器生成 serviceProvider, 然后通过 serviceProvider 获取Main Form的注册实例var serviceProvider =services.BuildServiceProvider();var formMain = serviceProvider.GetRequiredService(); //主动从容器中获取FormMain实例, 这是简洁写法// var formMain = (FormMain)serviceProvider.GetService(typeof(FormMain)); //更繁琐的写法Application.Run(formMain); }///

/// 在DI容器中注册所有的服务类型 /// /// private static void ConfigureServices(ServiceCollection services){//注册 FormMain 类services.AddScoped();//register configurationIConfigurationBuilder cfgBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")}.json", optional: true, reloadOnChange: false);IConfiguration configuration=cfgBuilder.Build();services.AddSingleton(configuration);//Create logger instancevar serilogLogger = new LoggerConfiguration().ReadFrom.Configuration(configuration).Enrich.FromLogContext().CreateLogger();//register loggerservices.AddLogging(builder => {object p = builder.AddSerilog(logger: serilogLogger, dispose: true);});}
}

}

FormMain.cs , 验证依赖注入的效果


using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Collector
{
public partial class FormMain : Form
{
private readonly IConfiguration _configuration;
private readonly ILogger _logger;

///

/// 为 FormMain 构造子增加两个形参, 构造子参数将由于DI容器自动注入/// /// /// 形参必须是 ILogger泛型类型, 不能是 ILogger 类型public FormMain(IConfiguration configuration, ILogger logger) {_configuration = configuration;_logger = logger;InitializeComponent();var connectionString = _configuration.GetConnectionString("oeeDb"); //从配置文件中读取oeeDb connectionString _logger.LogInformation(connectionString); //将connection String 写入到日志文件中}}

}

DI容器管理配置文件Section

上面示例, 我们通过 _configuration.GetConnectionString("oeeDb")? 可以拿到connectionString, 非常方便, 这主要是得益于.Net 已经类库已经考虑到在配置文件中存储 connectionString 是一个普遍的做法, 所以类库内置支持了.

如果在 appsettings.json 中存一些自定义的信息, 如何方便读取呢? 微软推荐的 Options 模式, 下面详细介绍.

首先安装库:

  • Microsoft.Extensions.Options.ConfigurationExtensions 库,? 为DI容器增加了从配置文件中实例化对象的能力, 即? serviceCollection.Configure(IConfiguration)
  • Microsoft.Extensions.Options 库,? 提供以强类型的方式读取configuration文件, 这是.Net中首选的读取configuration文件方式.

假设 appsettings.json 中要存放appKey和appSecret信息, 具体配置如下:

"AppServiceOptions": {"appKey": "appkey1","appSecret": "appSecret1"}

定义对应的 Poco Class,? 推荐后缀为 Options,

public class AppServiceOptions{public string AppKey { get; set; } = "";public string AppSecret { get; set; } = "";

}


注册函数 ConfigureServices()中,? 注册 AppServiceOptions 类, 告知DI容器, 要基于配置文件AppServiceOptions section来实例化

private static void ConfigureServices(ServiceCollection services){//注册 FormMain 类services.AddScoped();

//register configurationIConfigurationBuilder cfgBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")}.json", optional: true, reloadOnChange: false);IConfiguration configuration=cfgBuilder.Build();services.AddSingleton(configuration);//Create logger instancevar serilogLogger = new LoggerConfiguration().ReadFrom.Configuration(configuration).Enrich.FromLogContext().CreateLogger();//register loggerservices.AddLogging(builder => {object p = builder.AddSerilog(logger: serilogLogger, dispose: true);});//注册 AppServiceOptions 类, 告知DI容器, 要基于配置文件AppServiceOptions section来实例化services.AddOptions();services.Configure(configuration.GetSection("AppServiceOptions")); }


主动从DI容器中获取 AppServiceOptions 配置信息代码如下, 注意GetRequiredService函数的的泛型参数要使用 IOptions<> 包一下.

var appServiceOptionsWrapper&#61;serviceProvider.GetRequiredService>();AppServiceOptions appServiceOptions&#61; appServiceOptionsWrapper.Value;

将 AppServiceOptions 注入到 FormMain 的代码, 和主动从DI容器中获取 AppServiceOptions 实例一样, 都需要使用 IOptions<> 接口包一下构造子形参.

public partial class FormMain : Form{ private readonly IConfiguration _configuration; private readonly ILogger _logger;private AppServiceOptions _appServiceOptions;

///

/// 为 FormMain 构造子增加三个形参, 构造子参数将由于DI容器自动注入/// /// 形参必须是接口 IConfigurations/// 形参必须是 ILogger泛型类型, 不能是 ILogger 类型/// 形参必须是 IOptions 泛型接口 public FormMain(IConfiguration configuration, ILogger logger, IOptions appServiceOptionsWrapper) {_configuration &#61; configuration;_logger &#61; logger;_appServiceOptions &#61; appServiceOptionsWrapper.Value;InitializeComponent(); var connectionString &#61; _configuration.GetConnectionString("oeeDb"); //从配置文件中读取oeeDb connectionString _logger.LogInformation(connectionString); //将connection String 写入到日志文件中}private void button1_Click(object sender, EventArgs e){this.Text &#61; _appServiceOptions.AppKey;}
}



.net core 复杂 configuration Section 的读取

appsettings文件定义一个复杂的设置项, 顶层是一个json 数组, 里面又嵌套了另一个数组

"PlcDevices": [{"PlcDeviceId": "Plc1","IpAddress": "127.0.0.1","Port": 1234,"SlaveId": 1,"DataPoints": [{"ModbusAddress": 0,"EqpId": "eqp1"},{"ModbusAddress": 0,"EqpId": "eqp2"}]},

{"PlcDeviceId": "Plc2","IpAddress": "127.0.0.2","Port": 1234,"SlaveId": "2","DataPoints": [{"ModbusAddress": 0,"EqpId": "eqp3"},{"ModbusAddress": 0,"EqpId": "eqp4"}]
}


]

对应poco对象为:

public class PlcDevice
{public string IpAddress { get; set; } &#61; "";public int Port { get; set; } &#61; 0;public string PlcDeviceId { get; set; } &#61; "";public int SlaveId { get; set; } public List DataPoints { get; set; }

}

public class DataPoint
{ public int ModbusAddress { get; set; }
public string EqpId { get; set; } &#61; “”;
}

读取 json 的C# 代码:

services.AddOptions();
//实例化一个对应 PlcDevices json 数组对象, 使用了 IConfiguration.Get()
var PlcDeviceSettings&#61; configuration.GetSection("PlcDevices").Get>();
//或直接通过 service.Configure() 将appsettings 指定 section 放入DI 容器, 这里的T 为 List
services.Configure>(configuration.GetSection("PlcDevices"));

到此这篇关于.Net6开发winform程序使用依赖注入的文章就介绍到这了。希望对大家的学习有所帮助&#xff0c;也希望大家多多支持菜鸟教程https://www.piaodoo.com/。


推荐阅读
  • 本文介绍了Web学习历程记录中关于Tomcat的基本概念和配置。首先解释了Web静态Web资源和动态Web资源的概念,以及C/S架构和B/S架构的区别。然后介绍了常见的Web服务器,包括Weblogic、WebSphere和Tomcat。接着详细讲解了Tomcat的虚拟主机、web应用和虚拟路径映射的概念和配置过程。最后简要介绍了http协议的作用。本文内容详实,适合初学者了解Tomcat的基础知识。 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • Firefox火狐浏览器关闭到http://detectportal.firefox.com的流量问题解决办法
    本文介绍了使用Firefox火狐浏览器时出现关闭到http://detectportal.firefox.com的流量问题,并提供了解决办法。问题的本质是因为火狐默认开启了Captive portal技术,当连接需要认证的WiFi时,火狐会跳出认证界面。通过修改about:config中的network.captive-portal-service.en的值为false,可以解决该问题。 ... [详细]
  • 本文介绍了通过ABAP开发往外网发邮件的需求,并提供了配置和代码整理的资料。其中包括了配置SAP邮件服务器的步骤和ABAP写发送邮件代码的过程。通过RZ10配置参数和icm/server_port_1的设定,可以实现向Sap User和外部邮件发送邮件的功能。希望对需要的开发人员有帮助。摘要长度:184字。 ... [详细]
  • flowable工作流 流程变量_信也科技工作流平台的技术实践
    1背景随着公司业务发展及内部业务流程诉求的增长,目前信息化系统不能够很好满足期望,主要体现如下:目前OA流程引擎无法满足企业特定业务流程需求,且移动端体 ... [详细]
  • 本文介绍了将mysql从5.6.15升级到5.7.15的详细步骤,包括关闭访问、备份旧库、备份权限、配置文件备份、关闭旧数据库、安装二进制、替换配置文件以及启动新数据库等操作。 ... [详细]
  • Servlet多用户登录时HttpSession会话信息覆盖问题的解决方案
    本文讨论了在Servlet多用户登录时可能出现的HttpSession会话信息覆盖问题,并提供了解决方案。通过分析JSESSIONID的作用机制和编码方式,我们可以得出每个HttpSession对象都是通过客户端发送的唯一JSESSIONID来识别的,因此无需担心会话信息被覆盖的问题。需要注意的是,本文讨论的是多个客户端级别上的多用户登录,而非同一个浏览器级别上的多用户登录。 ... [详细]
  • Summarize function is doing alignment without timezone ?
    Hi.Imtryingtogetsummarizefrom00:00otfirstdayofthismonthametric, ... [详细]
  • 本文详细介绍了GetModuleFileName函数的用法,该函数可以用于获取当前模块所在的路径,方便进行文件操作和读取配置信息。文章通过示例代码和详细的解释,帮助读者理解和使用该函数。同时,还提供了相关的API函数声明和说明。 ... [详细]
  • 基于PgpoolII的PostgreSQL集群安装与配置教程
    本文介绍了基于PgpoolII的PostgreSQL集群的安装与配置教程。Pgpool-II是一个位于PostgreSQL服务器和PostgreSQL数据库客户端之间的中间件,提供了连接池、复制、负载均衡、缓存、看门狗、限制链接等功能,可以用于搭建高可用的PostgreSQL集群。文章详细介绍了通过yum安装Pgpool-II的步骤,并提供了相关的官方参考地址。 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
  • 本文介绍了如何在使用emacs时去掉ubuntu的alt键默认功能,并提供了相应的操作步骤和注意事项。 ... [详细]
  • 本文介绍了一种图片处理应用,通过固定容器来实现缩略图的功能。该方法可以实现等比例缩略、扩容填充和裁剪等操作。详细的实现步骤和代码示例在正文中给出。 ... [详细]
  • Spring框架《一》简介
    Spring框架《一》1.Spring概述1.1简介1.2Spring模板二、IOC容器和Bean1.IOC和DI简介2.三种通过类型获取bean3.给bean的属性赋值3.1依赖 ... [详细]
  • 大坑|左上角_pycharm连接服务器同步写代码(图文详细过程)
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了pycharm连接服务器同步写代码(图文详细过程)相关的知识,希望对你有一定的参考价值。pycharm连接服务 ... [详细]
author-avatar
纸鸢漫天飞舞
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有