common toString using reflection

本文介绍了一种Java对象转字符串的通用方法,通过反射获取对象的所有字段,并将其转换为字符串格式。此方法适用于复杂对象的序列化,简化了数据的输出过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

core class:

 

package com.itreply.oschina;

import java.lang.reflect.Field;


public class GeneralToString {
	public static String toString(Object obj) {
		
		if(obj == null) return "null";
		
		StringBuffer sb = new StringBuffer();
		
		Class clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		
		sb.append(clazz.getName() + "{");
		try{
			for(Field field :fields){
				field.setAccessible(true);
				sb.append("\n\t" + field.getName() + " = " + field.get(obj));
			}
		} catch(IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sb.append("\n}");
		
		return sb.toString();
	}
}

 

test :

 

package com.itreply.oschina;

public class ClassTest {
	public String publicStringField;
	public static int publicStaticStrField;
	
	private double privateIntField;
	private static float privateStaticFloatField;
	
	protected short protectedShortField;
	protected static long protectedStaticLongField;
	
	public ClassTest(String a, int b, double c, float d, short e, long f) {
		this.publicStringField = a;
		this.publicStaticStrField = b;
		this.privateIntField = c;
		this.privateStaticFloatField =d;
		this.protectedShortField = e;
		this.protectedStaticLongField = f;
	}
	
	public static void main(String[] args) {
		ClassTest c = new ClassTest("hello",10,10.88d,10.9f,(short)11,222222222222222L);
		System.out.println(GeneralToString.toString(c));
		
	}
}

 

 

//-------------------------------------------------------------- // Press F1 to get help about using script. // To access an object that is not located in the current class, start the call with Globals. // When using events and timers be cautious not to generate memoryleaks, // please see the help for more information. //--------------------------------------------------------------- namespace Neo.ApplicationFramework.Generated { using System.Windows.Forms; using System; using System.Drawing; using Neo.ApplicationFramework.Tools; using Neo.ApplicationFramework.Common.Graphics.Logic; using Neo.ApplicationFramework.Controls; using Neo.ApplicationFramework.Interfaces; using System.Data; using System.IO; using System.Diagnostics; using System.Reflection; using System.Net; using System.Text; using System.Collections; using System.Collections.Generic; using System.Data.SQLite; public partial class SQLiteDatabaseBasic { System.Threading.Thread _Thread; const string m_pathUSB = @"\Hard Disk\"; public SQLiteConnection m_SqliteConnection; private DataTable dt = new DataTable(); private DataTable dt_export=new DataTable(); // 一頁要顯示幾筆資料 (預設十筆) private int m_PageSize = 38; private int m_CurrentPageIndex = 1; private int m_TotalPage = 0; private int m_firstid=0; // //dxl private int m_TotalCount; public int PageSize { set{ m_PageSize = value;} } public int TotalCount { get{ return m_TotalCount;} set{ m_TotalCount = value;} } public int TotalPages { get{ return m_TotalPage;} } public int CurrentPageIndex { get{ return m_CurrentPageIndex;} set{ m_CurrentPageIndex = value;} } private void CalculateTotalPages(DataTable dt) { m_TotalCount= dt.Rows.Count; int rowCount = dt.Rows.Count; if(rowCount>0) { m_firstid=Convert.ToInt32( dt.Rows[rowCount-1][0]); } else { m_firstid=0; } m_TotalPage = rowCount / m_PageSize; if (rowCount % m_PageSize > 0) m_TotalPage += 1; } public string BuildSqlGetCurrentTableString(string tableName, int Fisrtitem, int Lastitem) { string tmpResult = string.Format("SELECT * FROM {0} WHERE ", tableName); tmpResult += string.Format("ID <= {0} AND ", Fisrtitem.ToString()); tmpResult += string.Format("ID >= {0} ORDER BY Time DESC", Lastitem.ToString()); return tmpResult; } public DataTable GetCurrentGPSDataTable(string tableName) { int m_Fisrtitem = 0; int m_Lastitem = 0; try { m_Fisrtitem = m_TotalCount - (m_PageSize * (m_CurrentPageIndex - 1)); if(m_Fisrtitem < m_PageSize) { m_Lastitem = 1; } else { m_Lastitem = m_Fisrtitem - m_PageSize + 1; } string buildstring = BuildSqlGetCurrentTableString(tableName, m_Fisrtitem+m_firstid, m_Lastitem+m_firstid); return Select(buildstring); } catch (Exception) { return null; } } public void Export(DataTable dtable) { if(dtable!=null) { dt_export=dtable.Copy(); _Thread = new System.Threading.Thread(new System.Threading.ThreadStart(MainThread)); _Thread.Priority = System.Threading.ThreadPriority.Normal; _Thread.IsBackground = true; _Thread.Start(); } } void MainThread() { if(!Directory.Exists(m_pathUSB)) //报错:未找到USB设备 { //MessageBox.Show("Not found USB Disk"); Globals.NoUSB.Show(); Globals.Tags.ExportButtonColor.Value = 0; return; } int ProgressBar=0; ExportData(dt_export,"",m_pathUSB,ref ProgressBar); //dxl 启动闪烁 Globals.Tags.Dxl_number.Value = 0; Globals.Tags.ExportButtonColor.Value = 1; } ///删除指定数据表的null public void DelectNull(string TableName,string ListName) { try // in case of problems { // Create SQL query, ask database, fetch data and fill data set string sqlString = string.Format("DELETE FROM {0} WHERE {1} is NULL",TableName,ListName); ConnectDataBase(sqlString); } catch (SQLiteException) { } } public void ConnectDataBase(string CMDstr) { if(ConnectToDataBase()) { try { SQLiteCommand command = new SQLiteCommand(CMDstr, m_SqliteConnection); command.ExecuteNonQuery(); } catch{} } DisconnectFromDataBase(); } public DataTable Select(string Commandstring) { if (ConnectToDataBase()) { try { SQLiteDataAdapter da = new SQLiteDataAdapter(Commandstring, m_SqliteConnection); dt.Rows.Clear(); dt.Columns.Clear(); da.Fill(dt); da.Dispose(); } catch (Exception ex) { DisconnectFromDataBase(); // MessageBox.Show(ex.Message); return null; } } DisconnectFromDataBase(); return dt; } public DataTable SelectDataLog(string tablename,string starttime,string endtime) { if (ConnectToDataBase()) { try { string Commandstring=string.Format("SELECT * FROM {2} where Time > '{0}' and Time < '{1}' ORDER BY Time DESC ",starttime,endtime,tablename); SQLiteDataAdapter da = new SQLiteDataAdapter(Commandstring, m_SqliteConnection); dt.Rows.Clear(); dt.Columns.Clear(); da.Fill(dt); CalculateTotalPages(dt); da.Dispose(); } catch (Exception ex) { DisconnectFromDataBase(); // MessageBox.Show(ex.Message); return null; } } DisconnectFromDataBase(); return dt; } public DataTable SelectDataLog(string tablename) { if (ConnectToDataBase()) { try { string Commandstring=string.Format("SELECT * FROM {0} ORDER BY Time DESC ",tablename); SQLiteDataAdapter da = new SQLiteDataAdapter(Commandstring, m_SqliteConnection); dt.Rows.Clear(); dt.Columns.Clear(); da.Fill(dt); CalculateTotalPages(dt); da.Dispose(); } catch (Exception ex) { DisconnectFromDataBase(); // MessageBox.Show(ex.Message); return null; } } DisconnectFromDataBase(); return dt; } /// <summary> /// 导出指定的数据表数据到指定文件中 /// </summary> /// <param name="DataTable">需要导出数据的数据表</param> /// <param name="CSVName">导出文件名称</param> /// <param name="ExportPath">导出路径</param> /// <param name="ProgressBar">导出进度显示</param> /// <returns></returns> public void ExportData(DataTable DataTable,string CSVName,string ExportPath,ref int ProgressBar) { try { if(ExportPath==string.Empty) { ExportPath = @"c:\project\"; } if(CSVName==string.Empty) { CSVName=DateTime.Now.ToString("yyyy-M-d HH.m.s")+DataTable.TableName.ToString(); //CSVName=DataTable.TableName.ToString(); } if (!Directory.Exists(ExportPath)) { //Directory.CreateDirectory(ExportPath); return; } //string FilePath = ExcecutingPath + @"project files\" + FileName.ToString() + ".csv"; //string FilePath = @"c:\" + FileName.ToString() + ".csv"; string FilePath =ExportPath+" "+CSVName.ToString()+".csv"; FileStream Fx = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.Write); StreamWriter writer = new StreamWriter(Fx, System.Text.Encoding.UTF8); //**********写表头内容,根据数据记录器项目重新填写******// string DataName=""; foreach (DataColumn column in DataTable.Columns) { DataName=DataName+column.ColumnName +","; } writer.WriteLine(DataName);//写数据表头 for (int i = 0; i < DataTable.Rows.Count; i++) { string writeLine = ""; for (int j = 0; j < DataTable.Columns.Count; j++) { writeLine += DataTable.Rows[i][j].ToString()+","; } if(writeLine!="") { writer.WriteLine(writeLine); //写数据到CSV文件 } ProgressBar=Convert.ToInt32(i*100/DataTable.Rows.Count); System.Threading. Thread.Sleep(100); } writer.Close(); Fx.Close(); ProgressBar=100; } catch(Exception ex) { // MessageBox.Show(ex.ToString()); } } private bool ConnectToDataBase() { if (m_SqliteConnection != null && m_SqliteConnection.State == ConnectionState.Open) return true; m_SqliteConnection = new SQLiteConnection(); m_SqliteConnection.ConnectionString = string.Format("data source={0}", Path.Combine(ExcecutingPath, "Database.db")); try { m_SqliteConnection.Open(); } catch (SQLiteException) { DisconnectFromDataBase(); return false; } return m_SqliteConnection.State == ConnectionState.Open; } private void DisconnectFromDataBase() { if (m_SqliteConnection != null) { if(m_SqliteConnection.State == ConnectionState.Open) { m_SqliteConnection.Close(); } m_SqliteConnection.Dispose(); m_SqliteConnection = null; } } private string ExcecutingPath { get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName); } } } }
05-30
using Blazored.LocalStorage; using DocumentFormat.OpenXml.ExtendedProperties; using DocumentFormat.OpenXml.Math; using log4net; using log4net.Config; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Server.Circuits; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using Org.BouncyCastle.Crypto.Engines; using Radzen; using Radzen.Blazor.Rendering; using SqlSugar.IOC; using System.IdentityModel.Tokens.Jwt; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Tewr.Blazor.FileReader; using WebApi.AgvServer.Api; using WebApi.AgvServer.Auth; using WebApi.AgvServer.Handles; using WebApi.AgvServer.Services; using WebApi.AgvServer.TimerService; using WebApi.AgvServer.Utility; using WebApi.AgvServer.Utility._AutoMapper; using WebApi.Common.Helper; using WebApi.Common.LicenceHelper; using WebApi.Common.Logger; using WebApi.IRepository; using WebApi.IRepository.Agvs; using WebApi.IRepository.Path; using WebApi.IRepository.Stations; using WebApi.IRepository.Tasks; using WebApi.IRepository.Users; using WebApi.IService; using WebApi.IService.AgvCommunication; using WebApi.IService.Agvs; using WebApi.IService.External; using WebApi.IService.Path; using WebApi.IService.Stations; using WebApi.IService.Tasks; using WebApi.IService.Users; using WebApi.Model.Common; using WebApi.Repository; using WebApi.Repository.Agvs; using WebApi.Repository.Path; using WebApi.Repository.Stations; using WebApi.Repository.Tasks; using WebApi.Repository.Users; using WebApi.Service; using WebApi.Service.AgvCommunication; using WebApi.Service.Agvs; using WebApi.Service.External; using WebApi.Service.Path; using WebApi.Service.Stations; using WebApi.Service.Tasks; using WebApi.Service.Users; using System.Net.Http; #region ���ÿ��ٱ༭ģʽ����windowsϵͳ��ע�͵� const int STD_INPUT_HANDLE = -10; const uint ENABLE_QUICK_EDIT_MODE = 0x0040; const uint ENABLE_INSERT_MODE = 0x0020; [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetStdHandle(int hConsoleHandle); [DllImport("kernel32.dll", SetLastError = true)] static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint mode); [DllImport("kernel32.dll", SetLastError = true)] static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint mode); #endregion #region ���ÿ��ٱ༭ģʽ����windowsϵͳ��ע�͵� IntPtr hStdin = GetStdHandle(STD_INPUT_HANDLE); uint mode; GetConsoleMode(hStdin, out mode); mode &= ~ENABLE_QUICK_EDIT_MODE;//�Ƴ����ٱ༭ģʽ mode &= ~ENABLE_INSERT_MODE; //�Ƴ�����ģʽ SetConsoleMode(hStdin, mode); #endregion #region �����windowsϵͳ�����ÿ���̨���ڱ��� [DllImport("kernel32.dll", SetLastError = true)] static extern bool SetConsoleTitle(string lpConsoleTitle); // ���ÿ���̨���ڱ��� SetConsoleTitle("AGV���ȹ���ϵͳ"); #endregion var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); builder.Services.AddHttpContextAccessor(); builder.Configuration.AddJsonFile("appsettings.json"); // 注册 HttpClientFactory builder.Services.AddHttpClient(); #region Swaggerע�� builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApi.AgvServer", Version = "v1" }); #region SwaggerGen ��Ȩ��� c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Description = "ֱ��������������Bearer {token}(ע���м��пո�)", Name = "Authorization", BearerFormat = "JWT", Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference= new OpenApiReference { Type=ReferenceType.SecurityScheme, Id="Bearer" } }, new string[]{ } } }); #endregion }); #endregion #region SqlSugar IOC var sqlInfo = builder.Configuration.GetSection(nameof(SQLInfo)).Get<SQLInfo>(); if (sqlInfo != null) { #region �������� //MySql = 0, //SqlServer = 1, //Sqlite = 2, //Oracle = 3, //PostgreSQL = 4, //Dm = 5, //Kdbndp = 6, //Oscar = 7, //MySqlConnector = 8, //Access = 9, //OpenGauss = 10, //QuestDB = 11, //HG = 12, //ClickHouse = 13, //GBase = 14, //Odbc = 15, //OceanBaseForOracle = 16, //TDengine = 17, //GaussDB = 18, //OceanBase = 19, //Tidb = 20, //Vastbase = 21, //PolarDB = 22, //Doris = 23, //Xugu = 24, //GoldenDB = 25, //TDSQLForPGODBC = 26, //TDSQL = 27, //HANA = 28, //DB2 = 29, //GaussDBNative = 30, //DuckDB = 31, //MongoDb = 32, //Custom = 900 #endregion builder.Services.AddSqlSugar(new IocConfig() { ConnectionString = sqlInfo.ConnStr, DbType = sqlInfo.SQLType, IsAutoCloseConnection = true,//�Զ��ͷ� }); #region �������� //services.ConfigurationSugar(db => //{ // db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices() // {//�������� // DataInfoCacheService = myCache, // }; // db.CurrentConnectionConfig.MoreSettings = new ConnMoreSettings() // { // IsAutoRemoveDataCache = true // }; //}); #endregion } #endregion #region ��֤ //��֤ע�� builder.Services.AddScoped<ImitateAuthStateProvider>(); builder.Services.AddScoped<AuthenticationStateProvider>(implementationFactory => implementationFactory.GetRequiredService<ImitateAuthStateProvider>()); //jwt builder.Services.AddScoped<JwtSecurityTokenHandler>(); #region httpclientע�� builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("http://localhost:9000") }); builder.Services.AddScoped<IAuthService, AuthService>(); builder.Services.AddScoped<AuthController>(); builder.Services.AddScoped<agvController>(); builder.Services.AddBlazoredLocalStorage(config => config.JsonSerializerOptions.WriteIndented = true); #endregion //jwt��֤ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { //ȡ��˽Կ var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"] ?? "Blazor!SecKey@okagv@vvip.GANLIHUA2025"); options.TokenValidationParameters = new TokenValidationParameters() { //��֤������ ValidateIssuer = true, ValidIssuer = builder.Configuration["Authentication:Issuer"], //��֤������ ValidateAudience = true, ValidAudience = builder.Configuration["Authentication:Audience"], //��֤�Ƿ���� ValidateLifetime = true, //��֤˽Կ IssuerSigningKey = new SymmetricSecurityKey(secretByte) }; }); //jwt��չ builder.Services.AddScoped<IJWTHelper, JWTHelper>(); #endregion #region ��ȡ��Ŀ���� var projectName = builder.Configuration["Authentication:Audience"]; if (projectName == null) { projectName = "Test"; } #endregion #region Radzenע�� //Radzen builder.Services.AddRadzenComponents(); builder.Services.AddFileReaderService(); builder.Services.AddRadzenCookieThemeService(options => { options.Name = $"{projectName}RadzenBlazorTheme"; // The name of the cookie options.Duration = TimeSpan.FromDays(365); // The duration of the cookie }); //services.AddServerSideBlazor().AddHubOptions(o => //{ // o.MaximumReceiveMessageSize = 64 * 1024; //}); builder.Services.AddScoped<DialogService>(); builder.Services.AddScoped<NotificationService>(); builder.Services.AddScoped<ContextMenuService>(); #endregion #region IOC����ע�� builder.Services.AddCustomIOC(); #endregion #region JWT��Ȩ //builder.Services.AddCustomJWT(); #endregion #region AutoMapper builder.Services.AddAutoMapper(typeof(CustomAutoMapperProfile)); #endregion #region log4net builder.Services.AddControllers().AddControllersAsServices(); Log4netHelper.Repository = LogManager.CreateRepository("NETCoreRepository"); XmlConfigurator.Configure(Log4netHelper.Repository, new System.IO.FileInfo(System.IO.Path.GetDirectoryName(typeof(Program).Assembly.Location) + "/Config/log4net.config")); #endregion #region net logger var verstion = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "unknown"; builder.Logging.AddLocalFileLogger(options => { options.SaveDays = 60; options.Verstion = verstion; }); #endregion #region cookie builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme). AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o => { o.LoginPath = new PathString("/Home/Login"); }); #endregion #region ��ȡappsetting���� try { //TaskInfo.IsAutoTask = ParamtersSettings.Load().IsAutoTask; //TaskInfo.IsAutoSendToAGV = ParamtersSettings.Load().IsAutoSendToNDC; //TaskInfo.LastKey = ParamtersSettings.Load().NncKey; //TaskInfo.TaskPause = ParamtersSettings.Load().TaskPause; //TaskInfo.SetTaskMode = ParamtersSettings.Load().SetTaskMode; //AGVMapInfo.mapInfo = ParamtersSettings.Load().mapInfo; //if (AGVMapInfo.mapInfo == null) //{ // AGVMapInfo.mapInfo = new AGVMapInfo(); // ParamtersSettings paramters = ParamtersSettings.Load(); // paramters.mapInfo = AGVMapInfo.mapInfo; // paramters.Save(); //} } catch { } #endregion #region ע��Licenceϵͳ��Ϣ�ļ� string computerFile = LicenceHelper.GetComputerInfoAndGenerateFile(); #endregion builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } //app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.MapControllers();//���ӿ��Ʋ����ս�� app.MapBlazorHub(); app.MapFallbackToPage("/_Host"); //app.MapFallbackToPage("/Login"); #region ���ػ��������� //const string CULTURE_CHINESE = "zh-CN"; //const string CULTURE_ENGLISTH = "en-US"; //const string CULTURE_RUSSIA = "ru-RU"; //app.UseRequestLocalization(options => //{ // var cultures = new[] { CULTURE_CHINESE, CULTURE_ENGLISTH, CULTURE_RUSSIA }; // options.AddSupportedCultures(cultures); // options.AddSupportedUICultures(cultures); // options.SetDefaultCulture(CULTURE_ENGLISTH); // // ��Http��Ӧʱ���� ��ǰ������Ϣ ���õ� Response Header��Content-Language �� // options.ApplyCurrentCultureToResponseHeaders = true; //}); #endregion app.UseAuthentication(); app.UseAuthorization(); app.Run(); #region �ⲿIO����ע�� public static class IOCExtend { /// <summary> /// ע���ⲿ���� /// </summary> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddCustomIOC(this IServiceCollection services) { #region �Ż�SignalIR�����紫�� services.AddSignalR().AddJsonProtocol(options => { options.PayloadSerializerOptions.WriteIndented = false; // ����JSON��������С������� }); #endregion services.AddSingleton<CircuitHandler, CustomCircuitHandler>(); services.AddSingleton<IUserInfoRepository, UserInfoRepository>(); services.AddSingleton<IRoleInfoRepository, RoleInfoRepository>(); services.AddSingleton<IRightInfoRepository, RightInfoRepository>(); services.AddSingleton<IRoleRightMappingRepository, RoleRightMappingRepository>(); services.AddSingleton<IAgvInfoRepository, AgvInfoRepository>(); services.AddSingleton<IAgvConfigInfoRepository, AgvConfigInfoRepository>(); services.AddSingleton<IAgvErrorInfoRepository, AgvErrorInfoRepository>(); services.AddSingleton<IProcessInfoRepository, ProcessInfoRepository>(); services.AddSingleton<ITaskInfoRepository, TaskInfoRepository>(); services.AddSingleton<IAreaInfoRepository, AreaInfoRepository>(); services.AddSingleton<IStationInfoRepository, StationInfoRepository>(); services.AddSingleton<ILogInfoRepository, LogInfoRepository>(); services.AddSingleton<IControlAreaInfoRepository, ControlAreaInfoRepository>(); services.AddSingleton<IPointInfoRepository, PointInfoRepository>(); services.AddSingleton<ILineInfoRepository, LineInfoRepository>(); services.AddSingleton<IDTCInfoRepository, DTCInfoRepository>(); services.AddSingleton<IStationTypeInfoRespository, StationTypeInfoRepository>(); services.AddSingleton<IStationTypeReleInfoRepository, StationTypeReleInfoRepository>(); services.AddSingleton<ISystemConfigInfoRepository, SystemConfigInfoRepository>(); services.AddSingleton<IUserInfoService, UserInfoService>(); services.AddSingleton<IRoleInfoService, RoleInfoService>(); services.AddSingleton<IRightInfoService, RightInfoService>(); services.AddSingleton<IRoleRightMappingService, RoleRightMappingService>(); services.AddSingleton<IAgvInfoService, AgvInfoService>(); services.AddSingleton<IAgvConfigInfoService, AgvConfigInfoService>(); services.AddSingleton<IAgvErrorInfoService, AgvErrorInfoService>(); services.AddSingleton<IProcessInfoService, ProcessInfoService>(); services.AddSingleton<ITaskInfoService, TaskInfoService>(); services.AddSingleton<IAreaInfoService, AreaInfoService>(); services.AddSingleton<IStationInfoService, StationInfoService>(); services.AddSingleton<ILogInfoService, LogInfoService>(); services.AddSingleton<IModbusService, ModbusService>(); services.AddSingleton<IControlButtonOpenTcpService, ControlButtonOpenTcpService>(); services.AddSingleton<IMqttClientService, MqttClientService>(); services.AddSingleton<INDCService, NDCService>(); services.AddSingleton<IControlAreaInfoService, ControlAreaInfoService>(); services.AddSingleton<IPointInfoService, PointInfoService>(); services.AddSingleton<ILineInfoService, LineInfoService>(); services.AddSingleton<IOpenTcpService, OpenTcpService>(); services.AddSingleton<IDTCInfoService, DTCInfoService>(); services.AddSingleton<IStationTypeInfoService, StationTypeInfoService>(); services.AddSingleton<IStationTypeReleInfoService, StationTypeReleInfoService>(); services.AddSingleton<IStationCommunicationService, StationCommunicationService>(); services.AddSingleton<IWcsHttpService, WcsHttpService>(); services.AddSingleton<ISystemConfigInfoService, SystemConfigService>(); services.AddScoped<NorthwindService>(); //services.AddSingleton<ISplitterCommunicationService, SplitterCommunicationService>(); //TimerService services.AddHostedService<NdcGlobalParameterTimerService>(); services.AddHostedService<TaskIssuedTimerService>(); services.AddHostedService<TaskUpdateToSqlTimerService>(); services.AddHostedService<ProcessUpdateToSqlTimerService>(); services.AddHostedService<CreateTaskTimerService>(); services.AddHostedService<AreaUpdateToSqlTimerService>(); services.AddHostedService<StationUpdateToSqlTimerService>(); services.AddHostedService<TaskLeaveSyncTimerService>(); services.AddHostedService<TaskEnterSyncTimerService>(); services.AddHostedService<OpenTcpTimerService>(); services.AddHostedService<StationCommunicationTimerService>(); services.AddHostedService<AgvRunTimeCalculateTimerService>(); services.AddHostedService<TaskRequestToWMSTimerService>(); services.AddHostedService<NdcLocalModeModbusTimerService>(); services.AddHostedService<DataInitializationTimerService>(); services.AddHostedService<LicenceTimerService>(); // services.AddHostedService<SplitterCommunicationTimerService>(); return services; } public static IServiceCollection AddCustomJWT(this IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF")), ValidateIssuer = true, ValidIssuer = "http://localhost:6000", ValidateAudience = true, ValidAudience = "http://localhost:8080", ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(value: 60) }; }); return services; } } #endregion 比如我这个代码要注册后再SplitterCommunicationService中使用该怎么注册
08-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值