文章来源: 学习通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文件.
仅适用于 Asp.Net core 和 Console 类应用
配置一个 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” ]
}
}
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); }///
}
}
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Collector
{
public partial class FormMain : Form
{
private readonly IConfiguration _configuration;
private readonly ILogger _logger;
///
}
上面示例, 我们通过 _configuration.GetConnectionString("oeeDb")? 可以拿到connectionString, 非常方便, 这主要是得益于.Net 已经类库已经考虑到在配置文件中存储 connectionString 是一个普遍的做法, 所以类库内置支持了.
如果在 appsettings.json 中存一些自定义的信息, 如何方便读取呢? 微软推荐的 Options 模式, 下面详细介绍.
首先安装库:
假设 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
主动从DI容器中获取 AppServiceOptions 配置信息代码如下, 注意GetRequiredService函数的的泛型参数要使用 IOptions<> 包一下.
var appServiceOptionsWrapper&#61;serviceProvider.GetRequiredService
将 AppServiceOptions 注入到 FormMain 的代码, 和主动从DI容器中获取 AppServiceOptions 实例一样, 都需要使用 IOptions<> 接口包一下构造子形参.
public partial class FormMain : Form{ private readonly IConfiguration _configuration; private readonly ILogger _logger;private AppServiceOptions _appServiceOptions;
///
}
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
}
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
services.Configure>(configuration.GetSection("PlcDevices"));
到此这篇关于.Net6开发winform程序使用依赖注入的文章就介绍到这了。希望对大家的学习有所帮助&#xff0c;也希望大家多多支持菜鸟教程https://www.piaodoo.com/。