修改代码

This commit is contained in:
Dai Mr 2024-11-13 00:30:24 +08:00
parent 5b2d325598
commit a304e908aa
37 changed files with 466 additions and 418 deletions

View File

@ -13,6 +13,7 @@ namespace Microsoft.Extensions.DependencyInjection
/// </summary> /// </summary>
public static IServiceCollection AddJobs(this IServiceCollection services, IConfiguration configuration) public static IServiceCollection AddJobs(this IServiceCollection services, IConfiguration configuration)
{ {
var interfaceType = typeof(IBaseJob); var interfaceType = typeof(IBaseJob);
var assembly = Assembly.GetExecutingAssembly(); var assembly = Assembly.GetExecutingAssembly();
@ -21,7 +22,12 @@ namespace Microsoft.Extensions.DependencyInjection
{ {
if (type.IsClass && type.GetInterfaces().Contains(interfaceType)) if (type.IsClass && type.GetInterfaces().Contains(interfaceType))
{ {
RecurringJob.AddOrUpdate(type.Name, ()=>((type as IBaseJob)!).Execute(), Cron.Minutely, TimeZoneInfo.Utc); var instance = services.GetServiceProviderOrNull().GetService(type);
//var instance = services.GetObject<IBaseJob>();
//var instance = Activator.CreateInstance(type);
RecurringJob.AddOrUpdate(type.Name, () => type.GetMethod("Execute").Invoke(instance,null), Cron.Minutely);
} }
} }
return services; return services;

View File

@ -1,15 +1,39 @@
using JiShe.CollectBus.Common.Interfaces; using System.Reflection;
using JiShe.CollectBus.Common.Models; using Hangfire;
using JiShe.CollectBus.Common.Jobs;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
using Volo.Abp.Modularity;
namespace JiShe.CollectBus.Application namespace JiShe.CollectBus.Application
{ {
public class JiSheCollectBusApplicationModule: IJiSheModule public class JiSheCollectBusApplicationModule: AbpModule
{ {
public void ConfigureServices(ServiceContext context) public override void ConfigureServices(ServiceConfigurationContext context)
{ {
var configuration = context.Configuration; //var configuration = context.Services.GetConfiguration();
context.Services.AddJobs(configuration); //context.Services.AddJobs(configuration);
}
public override void OnPostApplicationInitialization(ApplicationInitializationContext context)
{
var interfaceType = typeof(IBaseJob);
var assembly = Assembly.GetExecutingAssembly();
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsClass && type.GetInterfaces().Contains(interfaceType))
{
var instance = context.ServiceProvider.GetService(type);
//var instance = services.GetObject<IBaseJob>();
//var instance = Activator.CreateInstance(type);
RecurringJob.AddOrUpdate(type.Name, () => type.GetMethod("Execute").Invoke(instance, null), Cron.Minutely);
}
}
} }
} }
} }

View File

@ -6,10 +6,11 @@ using System.Threading.Tasks;
using JiShe.CollectBus.Common.Jobs; using JiShe.CollectBus.Common.Jobs;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Volo.Abp.DependencyInjection;
namespace JiShe.CollectBus.Application.Jobs namespace JiShe.CollectBus.Application.Jobs
{ {
public class TestJob : IBaseJob public class TestJob : IBaseJob,ISingletonDependency
{ {
private readonly ILogger<TestJob> _logger; private readonly ILogger<TestJob> _logger;
private readonly IConfiguration _configuration; private readonly IConfiguration _configuration;

View File

@ -1,24 +0,0 @@
using JiShe.CollectBus.Common.Interfaces;
namespace JiShe.CollectBus.Common.Attributes
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class DependsOnAttribute : Attribute
{
// 依赖的模块
public Type ModuleType { get; private init; }
public DependsOnAttribute(Type type)
{
ModuleType = type;
}
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public sealed class DependsOnAttribute<TModule> : DependsOnAttribute
where TModule : IJiSheModule
{
public DependsOnAttribute() : base(typeof(TModule))
{
}
}
}

View File

@ -11,15 +11,6 @@ namespace JiShe.CollectBus.Common.Extensions
/// </summary> /// </summary>
public static class CollectionExtensions public static class CollectionExtensions
{ {
/// <summary>
/// Checks whatever given collection object is null or has no item.
/// </summary>
[Description("检查给定的集合对象是否为null或没有项目")]
public static bool IsNullOrEmpty<T>([CanBeNull] this ICollection<T> source)
{
return source == null || source.Count <= 0;
}
/// <summary> /// <summary>
/// Adds an item to the collection if it's not already in the collection. /// Adds an item to the collection if it's not already in the collection.
/// </summary> /// </summary>

View File

@ -1,104 +1,104 @@
using JiShe.CollectBus.Common.Extensions.DependencyInjections; //using JiShe.CollectBus.Common.Extensions.DependencyInjections;
using System.Reflection; //using System.Reflection;
using JiShe.CollectBus.Common.Interfaces; //using JiShe.CollectBus.Common.Abstractions;
using Microsoft.Extensions.Hosting; //using Microsoft.Extensions.Hosting;
using System; //using System;
using Microsoft.Extensions.Configuration; //using Microsoft.Extensions.Configuration;
using Serilog; //using Serilog;
// ReSharper disable once CheckNamespace //// ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.DependencyInjection //namespace Microsoft.Extensions.DependencyInjection
{ //{
public static class DependencyInjectionExtensions // public static class DependencyInjectionExtensions
{ // {
public static IServiceCollection ModuleRegister(this IServiceCollection services, IConfiguration configuration) // public static IServiceCollection ModuleRegister(this IServiceCollection services, IConfiguration configuration)
{ // {
var assemblies = GetBinAssemblies(); // var assemblies = GetBinAssemblies();
foreach (var assembly in assemblies) // foreach (var assembly in assemblies)
{ // {
var allTypes = assembly.GetTypes(); // var allTypes = assembly.GetTypes();
foreach (var type in allTypes) // foreach (var type in allTypes)
{ // {
if (typeof(IJiSheModule).IsAssignableFrom(type) && type is { IsClass: true, IsAbstract: false }) // if (typeof(IJiSheModule).IsAssignableFrom(type) && type is { IsClass: true, IsAbstract: false })
{ // {
Log.Logger.Information($"正在加载模块{type.Name}..."); // Log.Logger.Information($"正在加载模块{type.Name}...");
var instance = Activator.CreateInstance(type); // var instance = Activator.CreateInstance(type);
_ = (type.GetMethod("ConfigureServices")?.Invoke(instance, [services, configuration])); // _ = (type.GetMethod("ConfigureServices")?.Invoke(instance, [services, configuration]));
} // }
} // }
} // }
return services; // return services;
} // }
public static IServiceCollection ServiceRegister(this IServiceCollection services) // public static IServiceCollection ServiceRegister(this IServiceCollection services)
{ // {
var assemblies = GetBinAssemblies(); // var assemblies = GetBinAssemblies();
foreach (var assembly in assemblies) // foreach (var assembly in assemblies)
{ // {
var allTypes = assembly.GetTypes(); // var allTypes = assembly.GetTypes();
foreach (var type in allTypes) // foreach (var type in allTypes)
{ // {
if (type is not { IsClass: true, IsAbstract: false }) continue; // if (type is not { IsClass: true, IsAbstract: false }) continue;
if (typeof(ISingletonDependency).IsAssignableFrom(type)) // if (typeof(ISingletonDependency).IsAssignableFrom(type))
{ // {
var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("ISingletonDependency") && !p.FullName.Contains("IDisposable")); // var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("ISingletonDependency") && !p.FullName.Contains("IDisposable"));
foreach (var interfaceType in interfaceTypes) // foreach (var interfaceType in interfaceTypes)
{ // {
Log.Logger.Information($"正在IOC注入ISingletonDependency {type.Name}..."); // Log.Logger.Information($"正在IOC注入ISingletonDependency {type.Name}...");
services.AddSingleton(interfaceType, type); // services.AddSingleton(interfaceType, type);
} // }
} // }
if (typeof(ITransientDependency).IsAssignableFrom(type)) // if (typeof(ITransientDependency).IsAssignableFrom(type))
{ // {
var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("ITransientDependency") && !p.FullName.Contains("IDisposable")); // var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("ITransientDependency") && !p.FullName.Contains("IDisposable"));
foreach (var interfaceType in interfaceTypes) // foreach (var interfaceType in interfaceTypes)
{ // {
Log.Logger.Information($"正在IOC注入ITransientDependency {type.Name}..."); // Log.Logger.Information($"正在IOC注入ITransientDependency {type.Name}...");
services.AddTransient(interfaceType, type); // services.AddTransient(interfaceType, type);
} // }
} // }
if (typeof(IScopedDependency).IsAssignableFrom(type)) // if (typeof(IScopedDependency).IsAssignableFrom(type))
{ // {
var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("IScopedDependency") && !p.FullName.Contains("IDisposable")); // var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("IScopedDependency") && !p.FullName.Contains("IDisposable"));
foreach (var interfaceType in interfaceTypes) // foreach (var interfaceType in interfaceTypes)
{ // {
Log.Logger.Information($"正在IOC注入IScopedDependency {type.Name}..."); // Log.Logger.Information($"正在IOC注入IScopedDependency {type.Name}...");
services.AddScoped(interfaceType, type); // services.AddScoped(interfaceType, type);
} // }
} // }
} // }
} // }
return services; // return services;
} // }
private static IEnumerable<Assembly> GetBinAssemblies() // private static IEnumerable<Assembly> GetBinAssemblies()
{ // {
var directory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory); // var directory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
if (!directory.Exists) return []; // if (!directory.Exists) return [];
var files = directory.GetFiles("JiShe.CollectBus.*.dll"); // var files = directory.GetFiles("JiShe.CollectBus.*.dll");
var assemblies = new List<Assembly>(); // var assemblies = new List<Assembly>();
foreach (var file in files) // foreach (var file in files)
{ // {
try // try
{ // {
var assembly = Assembly.LoadFrom(file.FullName); // var assembly = Assembly.LoadFrom(file.FullName);
assemblies.Add(assembly); // assemblies.Add(assembly);
} // }
catch (Exception ex) // catch (Exception ex)
{ // {
Console.WriteLine($"Error loading assembly from {file.FullName}: {ex.Message}"); // Console.WriteLine($"Error loading assembly from {file.FullName}: {ex.Message}");
} // }
} // }
return assemblies; // return assemblies;
} // }
} // }
} //}

View File

@ -1,6 +1,6 @@
namespace JiShe.CollectBus.Common.Extensions.DependencyInjections //namespace JiShe.CollectBus.Common.Extensions.DependencyInjections
{ //{
public interface IScopedDependency // public interface IScopedDependency
{ // {
} // }
} //}

View File

@ -1,6 +1,6 @@
namespace JiShe.CollectBus.Common.Extensions.DependencyInjections //namespace JiShe.CollectBus.Common.Extensions.DependencyInjections
{ //{
public interface ISingletonDependency // public interface ISingletonDependency
{ // {
} // }
} //}

View File

@ -1,6 +1,6 @@
namespace JiShe.CollectBus.Common.Extensions.DependencyInjections //namespace JiShe.CollectBus.Common.Extensions.DependencyInjections
{ //{
public interface ITransientDependency // public interface ITransientDependency
{ // {
} // }
} //}

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;

View File

@ -16,15 +16,7 @@ namespace JiShe.CollectBus.Common.Extensions
{ {
public static class StringExtensions public static class StringExtensions
{ {
/// <summary>Determines whether [is null or white space].</summary>
/// <param name="str">The string.</param>
/// <returns>
/// <c>true</c> if [is null or white space] [the specified string]; otherwise, <c>false</c>.</returns>
[Description("检查是否为NULL或空格")]
public static bool IsNullOrWhiteSpace(this string str)
{
return string.IsNullOrWhiteSpace(str);
}
/// <summary>Determines whether [is null or empty].</summary> /// <summary>Determines whether [is null or empty].</summary>
/// <param name="str">The string.</param> /// <param name="str">The string.</param>

View File

@ -1,16 +0,0 @@
using JiShe.CollectBus.Common.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace JiShe.CollectBus.Common.Interfaces
{
public interface IJiSheModule
{
/// <summary>
/// 模块中的依赖注入
/// </summary>
/// <param name="context">模块服务上下文</param>
void ConfigureServices(ServiceContext context);
}
}

View File

@ -9,9 +9,15 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="JetBrains.Annotations" Version="2024.2.0" /> <PackageReference Include="JetBrains.Annotations" Version="2024.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.1" /> <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog" Version="4.1.0" /> <PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Volo.Abp.Core" Version="8.3.3" />
</ItemGroup>
<ItemGroup>
<Folder Include="Abstractions\" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,4 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using JiShe.CollectBus.Common.Enums; using JiShe.CollectBus.Common.Enums;
namespace JiShe.CollectBus.Common.Models namespace JiShe.CollectBus.Common.Models
@ -16,14 +17,14 @@ namespace JiShe.CollectBus.Common.Models
public int CmdLength { get; set; } public int CmdLength { get; set; }
[Required(true)] [Required]
public string A { get; set; } public string A { get; set; }
public int MSA { get; set; } public int MSA { get; set; }
public AFN AFN { get; set; } public AFN AFN { get; set; }
[Required(true)] [Required]
public Seq Seq { get; set; } public Seq Seq { get; set; }
public int Pn { get; set; } public int Pn { get; set; }

View File

@ -1,4 +1,5 @@
 
using System.ComponentModel.DataAnnotations;
using JiShe.CollectBus.Common.Enums; using JiShe.CollectBus.Common.Enums;
namespace JiShe.CollectBus.Common.Models namespace JiShe.CollectBus.Common.Models
@ -12,10 +13,10 @@ namespace JiShe.CollectBus.Common.Models
public PRM PRM { get; set; } = PRM.; public PRM PRM { get; set; } = PRM.;
[Required(true)] [Required]
public string A { get; set; } public string A { get; set; }
[Required(true)] [Required]
public Seq Seq { get; set; } public Seq Seq { get; set; }
public int MSA { get; set; } = 0; public int MSA { get; set; } = 0;

View File

@ -1,29 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace JiShe.CollectBus.Common.Models
{
public class ServiceContext
{
internal ServiceContext(IServiceCollection serviceCollection, IConfiguration configuration)
{
Services = serviceCollection;
Configuration = configuration;
}
/// <summary>
/// 依赖注入服务
/// </summary>
public IServiceCollection Services { get; }
/// <summary>
/// 配置
/// </summary>
public IConfiguration Configuration { get; }
}
}

View File

@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace JiShe.CollectBus.Common
{
public class RequiredAttribute:Attribute
{
public bool IsRequired { get; private set; }
public RequiredAttribute(bool isRequired)
{
IsRequired = isRequired;
}
}
}

View File

@ -1,94 +1,92 @@
using JiShe.CollectBus.Common.Extensions.DependencyInjections; //using JiShe.CollectBus.Common.Extensions.DependencyInjections;
using JiShe.CollectBus.Protocol.Contracts.Attributes; //using JiShe.CollectBus.Protocol.Contracts.Attributes;
using System.Reflection; //using System.Reflection;
using JiShe.CollectBus.Common.Interfaces; //using TouchSocket.Core;
using TouchSocket.Core; //using System;
using Microsoft.Extensions.Hosting; //using Serilog;
using System;
using Serilog;
// ReSharper disable once CheckNamespace //// ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.DependencyInjection //namespace Microsoft.Extensions.DependencyInjection
{ //{
public static class DependencyInjectionExtensions // public static class DependencyInjectionExtensions
{ // {
public static void PluginServiceRegister(this IServiceCollection services, string pluginPath = "") // public static void PluginServiceRegister(this IServiceCollection services, string pluginPath = "")
{ // {
if (pluginPath.IsNullOrWhiteSpace()) // if (pluginPath.IsNullOrWhiteSpace())
{ // {
pluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"); // pluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
} // }
var assemblies = GetAssembliesFromFolder(pluginPath); // var assemblies = GetAssembliesFromFolder(pluginPath);
foreach (var assembly in assemblies) // foreach (var assembly in assemblies)
{ // {
var allTypes = assembly.GetTypes(); // var allTypes = assembly.GetTypes();
foreach (var type in allTypes) // foreach (var type in allTypes)
{ // {
if (typeof(ISingletonDependency).IsAssignableFrom(type) && type is { IsClass: true, IsAbstract: false }) // if (typeof(ISingletonDependency).IsAssignableFrom(type) && type is { IsClass: true, IsAbstract: false })
{ // {
var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("ISingletonDependency")); // var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("ISingletonDependency"));
foreach (var interfaceType in interfaceTypes) // foreach (var interfaceType in interfaceTypes)
{ // {
var attr = type.GetCustomAttribute<ProtocolNameAttribute>(); // var attr = type.GetCustomAttribute<ProtocolNameAttribute>();
if (attr == null) continue; // if (attr == null) continue;
Log.Logger.Information($"正在加载插件{attr.Name}..."); // Log.Logger.Information($"正在加载插件{attr.Name}...");
var serviceDescriptor = new ServiceDescriptor(interfaceType, attr.Name, type, ServiceLifetime.Singleton); // var serviceDescriptor = new ServiceDescriptor(interfaceType, attr.Name, type, ServiceLifetime.Singleton);
services.Add(serviceDescriptor); // services.Add(serviceDescriptor);
} // }
} // }
if (typeof(ITransientDependency).IsAssignableFrom(type) && type is { IsClass: true, IsAbstract: false }) // if (typeof(ITransientDependency).IsAssignableFrom(type) && type is { IsClass: true, IsAbstract: false })
{ // {
var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("ITransientDependency")); // var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("ITransientDependency"));
foreach (var interfaceType in interfaceTypes) // foreach (var interfaceType in interfaceTypes)
{ // {
var attr = type.GetCustomAttribute<ProtocolNameAttribute>(); // var attr = type.GetCustomAttribute<ProtocolNameAttribute>();
if (attr == null) continue; // if (attr == null) continue;
Log.Logger.Information($"正在加载插件{attr.Name}..."); // Log.Logger.Information($"正在加载插件{attr.Name}...");
var serviceDescriptor = new ServiceDescriptor(interfaceType, attr.Name, type, ServiceLifetime.Transient); // var serviceDescriptor = new ServiceDescriptor(interfaceType, attr.Name, type, ServiceLifetime.Transient);
services.Add(serviceDescriptor); // services.Add(serviceDescriptor);
} // }
} // }
if (typeof(IScopedDependency).IsAssignableFrom(type) && type is { IsClass: true, IsAbstract: false }) // if (typeof(IScopedDependency).IsAssignableFrom(type) && type is { IsClass: true, IsAbstract: false })
{ // {
var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("IScopedDependency")); // var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("IScopedDependency"));
foreach (var interfaceType in interfaceTypes) // foreach (var interfaceType in interfaceTypes)
{ // {
var attr = type.GetCustomAttribute<ProtocolNameAttribute>(); // var attr = type.GetCustomAttribute<ProtocolNameAttribute>();
if (attr == null) continue; // if (attr == null) continue;
Log.Logger.Information($"正在加载插件{attr.Name}..."); // Log.Logger.Information($"正在加载插件{attr.Name}...");
var serviceDescriptor = new ServiceDescriptor(interfaceType, attr.Name, type, ServiceLifetime.Scoped); // var serviceDescriptor = new ServiceDescriptor(interfaceType, attr.Name, type, ServiceLifetime.Scoped);
services.Add(serviceDescriptor); // services.Add(serviceDescriptor);
} // }
} // }
} // }
} // }
} // }
private static IEnumerable<Assembly> GetAssembliesFromFolder(string folderPath) // private static IEnumerable<Assembly> GetAssembliesFromFolder(string folderPath)
{ // {
var directory = new DirectoryInfo(folderPath); // var directory = new DirectoryInfo(folderPath);
if (!directory.Exists) return []; // if (!directory.Exists) return [];
var files = directory.GetFiles("*.dll"); // var files = directory.GetFiles("*.dll");
var assemblies = new List<Assembly>(); // var assemblies = new List<Assembly>();
foreach (var file in files) // foreach (var file in files)
{ // {
try // try
{ // {
var assembly = Assembly.LoadFrom(file.FullName); // var assembly = Assembly.LoadFrom(file.FullName);
assemblies.Add(assembly); // assemblies.Add(assembly);
} // }
catch (Exception ex) // catch (Exception ex)
{ // {
Console.WriteLine($"Error loading assembly from {file.FullName}: {ex.Message}"); // Console.WriteLine($"Error loading assembly from {file.FullName}: {ex.Message}");
} // }
} // }
return assemblies; // return assemblies;
} // }
} // }
} //}

View File

@ -1,52 +1,56 @@
using JiShe.CollectBus.Core.Plugins; using System.Reflection;
using JiShe.CollectBus.Common.Extensions;
using JiShe.CollectBus.Core.Plugins;
using JiShe.CollectBus.Core.Services; using JiShe.CollectBus.Core.Services;
using JiShe.CollectBus.Protocol.Contracts.Adapters; using JiShe.CollectBus.Protocol.Contracts.Adapters;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using TouchSocket.Core; using TouchSocket.Core;
using TouchSocket.Sockets; using TouchSocket.Sockets;
using Volo.Abp.Modularity;
// ReSharper disable once CheckNamespace // ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.DependencyInjection namespace Microsoft.Extensions.DependencyInjection
{ {
public static class ServiceCollectionExtensions public static class ServiceCollectionExtensions
{ {
/// <summary> public static void AddPluginApplications(this IServiceCollection services, string pluginPath = "")
/// 添加TcpService服务。
/// </summary>
public static IServiceCollection AddTcp(this IServiceCollection services, IConfiguration configuration)
{ {
services.AddTcpService(config => if (string.IsNullOrWhiteSpace(pluginPath))
{ {
config.SetListenIPHosts(int.Parse(configuration["TCP:ClientPort"] ?? "10500")) pluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
//.SetTcpDataHandlingAdapter(()=>new StandardFixedHeaderDataHandlingAdapter()) }
.ConfigurePlugins(a => var assemblies = GetAssembliesFromFolder(pluginPath);
foreach (var assembly in assemblies)
{ {
a.Add<TcpClosePlugin>(); var applicationServiceType = assembly.GetTypes()
a.Add<TcpServicePlugin>(); .FirstOrDefault(a => a.IsClass && !a.IsAbstract && typeof(AbpModule).IsAssignableFrom(a));
a.Add<BusService>(); services.AddApplication(applicationServiceType);
}); }
});
return services;
} }
private static IEnumerable<Assembly> GetAssembliesFromFolder(string folderPath)
{
var directory = new DirectoryInfo(folderPath);
if (!directory.Exists) return [];
/// <summary> var files = directory.GetFiles("*.dll");
/// 添加UdpService服务。
/// </summary> var assemblies = new List<Assembly>();
public static IServiceCollection AddUdp(this IServiceCollection services, IConfiguration configuration) foreach (var file in files)
{ {
services.AddUdpSession(config => try
{ {
config.SetBindIPHost(int.Parse(configuration["UDP:ClientPort"] ?? "10500")) var assembly = Assembly.LoadFrom(file.FullName);
.ConfigurePlugins(a => assemblies.Add(assembly);
}
catch (Exception ex)
{ {
a.Add<UdpServicePlugin>(); Console.WriteLine($"Error loading assembly from {file.FullName}: {ex.Message}");
a.Add<BusService>(); }
}) }
.UseBroadcast()
.SetUdpDataHandlingAdapter(() => new NormalUdpDataHandlingAdapter()); return assemblies;
});
return services;
} }
} }
} }

View File

@ -39,6 +39,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\JiShe.CollectBus.Application\JiShe.CollectBus.Application.csproj" />
<ProjectReference Include="..\JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj" /> <ProjectReference Include="..\JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj" />
<ProjectReference Include="..\JiShe.CollectBus.Core\JiShe.CollectBus.Core.csproj" /> <ProjectReference Include="..\JiShe.CollectBus.Core\JiShe.CollectBus.Core.csproj" />
<ProjectReference Include="..\JiShe.CollectBus.EntityFrameworkCore\JiShe.CollectBus.EntityFrameworkCore.csproj" /> <ProjectReference Include="..\JiShe.CollectBus.EntityFrameworkCore\JiShe.CollectBus.EntityFrameworkCore.csproj" />
@ -47,6 +48,9 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Update="Plugins\JiShe.CollectBus.Protocol.Demo.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Plugins\JiShe.CollectBus.Protocol.dll"> <None Update="Plugins\JiShe.CollectBus.Protocol.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>

View File

@ -1,7 +1,9 @@
using Microsoft.Extensions.Configuration; using JiShe.CollectBus.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Serilog; using Serilog;
using Volo.Abp;
namespace JiShe.CollectBus.Console namespace JiShe.CollectBus.Console
{ {
@ -18,6 +20,7 @@ namespace JiShe.CollectBus.Console
CreateHostBuilder(args).Build().Run(); CreateHostBuilder(args).Build().Run();
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -52,16 +55,17 @@ namespace JiShe.CollectBus.Console
lc.ReadFrom.Configuration(configuration) lc.ReadFrom.Configuration(configuration)
.ReadFrom.Services(context); .ReadFrom.Services(context);
}); });
services.ServiceRegister() services.AddApplication<JiSheCollectBusCoreModule>();
.ModuleRegister(configuration) services.AddPluginApplications();
.PluginServiceRegister();
services.AddTcp(configuration);
//services.AddUdp(configuration);
services.AddStackExchangeRedisCache(options => services.AddStackExchangeRedisCache(options =>
{ {
options.Configuration = configuration["RedisCache:ConnectionString"]; options.Configuration = configuration["RedisCache:ConnectionString"];
options.InstanceName = configuration["RedisCache:InstanceName"]; options.InstanceName = configuration["RedisCache:InstanceName"];
}); });
//var app = AbpApplicationFactory.Create<JiSheCollectBusCoreModule>();
//app.Initialize();
} }
} }
} }

View File

@ -0,0 +1,50 @@
using JiShe.CollectBus.Core.Plugins;
using JiShe.CollectBus.Core.Services;
using JiShe.CollectBus.EntityFrameworkCore;
using JiShe.CollectBus.RabbitMQ;
using Microsoft.Extensions.DependencyInjection;
using TouchSocket.Core;
using TouchSocket.Sockets;
using Volo.Abp;
using Volo.Abp.Modularity;
namespace JiShe.CollectBus.Core
{
[DependsOn(typeof(JiSheCollectBusEntityFrameworkCoreModule),
typeof(JiSheCollectBusRabbitMqModule))]
public class JiSheCollectBusCoreModule : AbpModule
{
public override async void ConfigureServices(ServiceConfigurationContext context)
{
var configuration = context.Services.GetConfiguration();
context.Services.AddTcpService(config =>
{
config.SetListenIPHosts(int.Parse(configuration["TCP:ClientPort"] ?? "10500"))
//.SetTcpDataHandlingAdapter(()=>new StandardFixedHeaderDataHandlingAdapter())
.ConfigurePlugins(a =>
{
a.Add<TcpClosePlugin>();
a.Add<TcpServicePlugin>();
a.Add<BusService>();
});
});
context.Services.AddUdpSession(config =>
{
config.SetBindIPHost(int.Parse(configuration["UDP:ClientPort"] ?? "10500"))
.ConfigurePlugins(a =>
{
a.Add<UdpServicePlugin>();
a.Add<BusService>();
})
.UseBroadcast()
.SetUdpDataHandlingAdapter(() => new NormalUdpDataHandlingAdapter());
});
}
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
}
}
}

View File

@ -16,14 +16,16 @@ namespace JiShe.CollectBus.Core.Plugins
private readonly ILogger<TcpServicePlugin> _logger; private readonly ILogger<TcpServicePlugin> _logger;
public readonly IMongoRepository<MessageReceivedHeartbeatEvent> _mongoHeartbeatRepository; public readonly IMongoRepository<MessageReceivedHeartbeatEvent> _mongoHeartbeatRepository;
public readonly IMongoRepository<MessageReceivedLoginEvent> _mongoLoginRepository; public readonly IMongoRepository<MessageReceivedLoginEvent> _mongoLoginRepository;
public readonly IServiceProvider _serviceProvider;
public TcpServicePlugin(INSender nSender, ILogger<TcpServicePlugin> logger,IMongoRepository<MessageReceivedHeartbeatEvent> mongoHeartbeatRepository, IMongoRepository<MessageReceivedLoginEvent> mongoLoginRepository) public TcpServicePlugin(INSender nSender, ILogger<TcpServicePlugin> logger,IMongoRepository<MessageReceivedHeartbeatEvent> mongoHeartbeatRepository, IMongoRepository<MessageReceivedLoginEvent> mongoLoginRepository, IServiceProvider serviceProvider)
{ {
_nSender = nSender; _nSender = nSender;
_logger = logger; _logger = logger;
_mongoHeartbeatRepository = mongoHeartbeatRepository; _mongoHeartbeatRepository = mongoHeartbeatRepository;
_mongoLoginRepository = mongoLoginRepository; _mongoLoginRepository = mongoLoginRepository;
_serviceProvider = serviceProvider;
} }

View File

@ -0,0 +1,11 @@
using Volo.Abp.Modularity;
namespace JiShe.CollectBus.EntityFrameworkCore
{
public class JiSheCollectBusEntityFrameworkCoreModule: AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
}
}
}

View File

@ -17,11 +17,14 @@
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" /> <PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" /> <PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" /> <PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="Volo.Abp.AspNetCore" Version="8.3.3" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\JiShe.CollectBus.Application\JiShe.CollectBus.Application.csproj" />
<ProjectReference Include="..\JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj" /> <ProjectReference Include="..\JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj" />
<ProjectReference Include="..\JiShe.CollectBus.Core\JiShe.CollectBus.Core.csproj" /> <ProjectReference Include="..\JiShe.CollectBus.Core\JiShe.CollectBus.Core.csproj" />
<ProjectReference Include="..\JiShe.CollectBus.EntityFrameworkCore\JiShe.CollectBus.EntityFrameworkCore.csproj" /> <ProjectReference Include="..\JiShe.CollectBus.EntityFrameworkCore\JiShe.CollectBus.EntityFrameworkCore.csproj" />

View File

@ -2,6 +2,8 @@
using Hangfire.Dashboard.BasicAuthorization; using Hangfire.Dashboard.BasicAuthorization;
using Hangfire.HttpJob; using Hangfire.HttpJob;
using Hangfire.MySql; using Hangfire.MySql;
using JiShe.CollectBus.Application;
using JiShe.CollectBus.Core;
namespace JiShe.CollectBus.Host namespace JiShe.CollectBus.Host
{ {
@ -33,11 +35,12 @@ namespace JiShe.CollectBus.Host
config.UseHangfireHttpJob(); config.UseHangfireHttpJob();
}); });
services.AddHangfireServer(); services.AddHangfireServer();
services.ServiceRegister().ModuleRegister(configuration); services.AddApplication<JiSheCollectBusApplicationModule>();
} }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ {
app.InitializeApplication();
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
@ -83,6 +86,7 @@ namespace JiShe.CollectBus.Host
{ {
endpoint.MapControllers(); endpoint.MapControllers();
}); });
} }
} }

View File

@ -27,7 +27,8 @@
}, },
"ConnectionStrings": { "ConnectionStrings": {
"Default": "Data Source=192.168.111.248;Port=3306;Database=JiSheCollectBus;uid=root;pwd=123456abcD;charset=utf8mb4;Allow User Variables=true;AllowLoadLocalInfile=true" //"Default": "Data Source=192.168.111.248;Port=3306;Database=JiSheCollectBus;uid=root;pwd=123456abcD;charset=utf8mb4;Allow User Variables=true;AllowLoadLocalInfile=true",
"Default": "Data Source=localhost;Port=3306;Database=JiSheCollectBus;uid=root;pwd=123456abcD;charset=utf8mb4;Allow User Variables=true;AllowLoadLocalInfile=true"
}, },
"MongoSettings": { "MongoSettings": {
"Connection": "mongodb://backups_admin:jishe_mongodb_backups@118.190.144.92:27037", "Connection": "mongodb://backups_admin:jishe_mongodb_backups@118.190.144.92:27037",

View File

@ -1,12 +1,11 @@
using JiShe.CollectBus.Common.Interfaces; using Microsoft.Extensions.DependencyInjection;
using JiShe.CollectBus.Common.Models; using Volo.Abp.Modularity;
using Microsoft.Extensions.DependencyInjection;
namespace JiShe.CollectBus.MongoDB namespace JiShe.CollectBus.MongoDB
{ {
public class JiSheCollectBusMongoDbModule: IJiSheModule public class JiSheCollectBusMongoDbModule: AbpModule
{ {
public void ConfigureServices(ServiceContext context) public override void ConfigureServices(ServiceConfigurationContext context)
{ {
context.Services.AddSingleton<IMongoContext, MongoContext>(); context.Services.AddSingleton<IMongoContext, MongoContext>();
context.Services.AddSingleton<IUnitOfWork, UnitOfWork>(); context.Services.AddSingleton<IUnitOfWork, UnitOfWork>();

View File

@ -1,5 +1,4 @@
using JiShe.CollectBus.Common.Extensions.DependencyInjections; using MongoDB.Bson;
using MongoDB.Bson;
using MongoDB.Driver; using MongoDB.Driver;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;

View File

@ -1,11 +1,5 @@
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using MongoDB.Driver; using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JiShe.CollectBus.Common.Extensions.DependencyInjections;
namespace JiShe.CollectBus.MongoDB namespace JiShe.CollectBus.MongoDB
{ {

View File

@ -1,5 +1,4 @@
using JiShe.CollectBus.Common.Extensions.DependencyInjections; using MongoDB.Driver;
using MongoDB.Driver;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;

View File

@ -0,0 +1,20 @@
using JiShe.CollectBus.Protocol.Contracts.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
using Volo.Abp.Modularity;
namespace JiShe.CollectBus.Protocol.Demo
{
public class JiSheCollectBusTestProtocolModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddKeyedSingleton<IProtocolPlugin, TestProtocolPlugin>("Test");
}
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
}
}
}

View File

@ -1,24 +1,21 @@
using JiShe.CollectBus.Common.Extensions.DependencyInjections; using JiShe.CollectBus.Protocol.Contracts.Abstracts;
using JiShe.CollectBus.MongoDB;
using JiShe.CollectBus.Protocol.Contracts.Abstracts;
using JiShe.CollectBus.Protocol.Contracts.Attributes; using JiShe.CollectBus.Protocol.Contracts.Attributes;
using JiShe.CollectBus.Protocol.Contracts.Models; using JiShe.CollectBus.Protocol.Contracts.Models;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using TouchSocket.Sockets;
namespace JiShe.CollectBus.Protocol.Test namespace JiShe.CollectBus.Protocol.Demo
{ {
[ProtocolName("TestProtocol")] [ProtocolName("TestProtocol")]
public class TestProtocolPlugin : BaseProtocolPlugin, ISingletonDependency public class TestProtocolPlugin : BaseProtocolPlugin
{ {
public TestProtocolPlugin(ILogger<BaseProtocolPlugin> logger) : base(logger) public TestProtocolPlugin(ILogger<BaseProtocolPlugin> logger) : base(logger)
{ {
} }
public override Task<ProtocolInfo> GetAsync() public override async Task<ProtocolInfo> GetAsync()
{ {
throw new NotImplementedException(); var info = new ProtocolInfo("Test", "376.1", "TCP", "376.1协议", "DTS1980");
return await Task.FromResult(info);
} }
public override Task AnalyzeAsync(MessageReceivedEvent messageReceivedEvent, Action<byte[]>? sendAction = null) public override Task AnalyzeAsync(MessageReceivedEvent messageReceivedEvent, Action<byte[]>? sendAction = null)

View File

@ -0,0 +1,21 @@
using JiShe.CollectBus.Protocol.Contracts.Interfaces;
using JiShe.CollectBus.RabbitMQ;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
using Volo.Abp.Modularity;
namespace JiShe.CollectBus.Protocol
{
public class JiSheCollectBusProtocolModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddKeyedSingleton<IProtocolPlugin, StandardProtocolPlugin>("Standard");
}
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
}
}
}

View File

@ -1,17 +1,17 @@
using JiShe.CollectBus.Common.Enums; using JiShe.CollectBus.Common.Enums;
using JiShe.CollectBus.Common.Extensions; using JiShe.CollectBus.Common.Extensions;
using JiShe.CollectBus.Common.Extensions.DependencyInjections;
using JiShe.CollectBus.Common.Models; using JiShe.CollectBus.Common.Models;
using JiShe.CollectBus.Protocol.Contracts.Abstracts; using JiShe.CollectBus.Protocol.Contracts.Abstracts;
using JiShe.CollectBus.Protocol.Contracts.Attributes; using JiShe.CollectBus.Protocol.Contracts.Attributes;
using JiShe.CollectBus.Protocol.Contracts.Models; using JiShe.CollectBus.Protocol.Contracts.Models;
using JiShe.CollectBus.RabbitMQ.Senders; using JiShe.CollectBus.RabbitMQ.Senders;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Volo.Abp.DependencyInjection;
namespace JiShe.CollectBus.Protocol namespace JiShe.CollectBus.Protocol
{ {
[ProtocolName("StandardProtocol")] [ProtocolName("StandardProtocol")]
public class StandardProtocolPlugin(INSender nSender, ILogger<BaseProtocolPlugin> logger) : BaseProtocolPlugin(logger), ISingletonDependency public class StandardProtocolPlugin(INSender nSender, ILogger<BaseProtocolPlugin> logger) : BaseProtocolPlugin(logger)
{ {
public override async Task<ProtocolInfo> GetAsync() public override async Task<ProtocolInfo> GetAsync()
{ {

View File

@ -1,19 +1,16 @@
using JiShe.CollectBus.Common.Interfaces; using JiShe.CollectBus.RabbitMQ.Consumers;
using JiShe.CollectBus.Common.Models;
using JiShe.CollectBus.RabbitMQ.Consumers;
using MassTransit; using MassTransit;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Volo.Abp;
using System.Data; using Volo.Abp.Modularity;
namespace JiShe.CollectBus.RabbitMQ namespace JiShe.CollectBus.RabbitMQ
{ {
public class JiSheCollectBusRabbitMqModule: IJiSheModule public class JiSheCollectBusRabbitMqModule: AbpModule
{ {
public void ConfigureServices(ServiceContext context) public override void ConfigureServices(ServiceConfigurationContext context)
{ {
var configuration = context.Configuration; var configuration = context.Services.GetConfiguration();
context.Services.AddMassTransit(x => context.Services.AddMassTransit(x =>
{ {
x.AddConsumer<MessageReceivedConsumer>(cfg => x.AddConsumer<MessageReceivedConsumer>(cfg =>
@ -51,7 +48,7 @@ namespace JiShe.CollectBus.RabbitMQ
}); });
// 消息接收队列 // 消息接收队列
cfg.ReceiveEndpoint(configuration["MQ:Queue:Received"] ?? string.Empty,configurator => cfg.ReceiveEndpoint(configuration["MQ:Queue:Received"] ?? string.Empty, configurator =>
{ {
configurator.ConfigureConsumeTopology = false; configurator.ConfigureConsumeTopology = false;
configurator.Consumer<MessageReceivedConsumer>(c); configurator.Consumer<MessageReceivedConsumer>(c);
@ -81,5 +78,9 @@ namespace JiShe.CollectBus.RabbitMQ
}); });
}); });
} }
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
}
} }
} }

View File

@ -1,6 +1,6 @@
using MassTransit; using MassTransit;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using JiShe.CollectBus.Common.Extensions.DependencyInjections; using Volo.Abp.DependencyInjection;
namespace JiShe.CollectBus.RabbitMQ.Senders namespace JiShe.CollectBus.RabbitMQ.Senders
{ {