新增driver层

zw
smartwyy 7 months ago
parent adac9e7722
commit 6f0ab1b44e

@ -0,0 +1,8 @@
using Autofac;
namespace HybirdFrameworkCore.Autofac;
public class AppInfo
{
public static ILifetimeScope Container { get; set; }
}

@ -0,0 +1,11 @@
namespace HybirdFrameworkCore.Autofac.Attribute;
public class OrderAttribute : System.Attribute
{
public readonly int Order;
public OrderAttribute(int order)
{
this.Order = order;
}
}

@ -17,6 +17,7 @@ namespace HybirdFrameworkCore.Autofac
#region 带有接口层的服务注入
var repositoryDllFile = Path.Combine(basePath, "HybirdFrameworkRepository.dll");
var driverDllFile = Path.Combine(basePath, "HybirdFrameworkDriver.dll");
var servicesDllFile = Path.Combine(basePath, "HybirdFrameworkServices.dll");
if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile)))
@ -25,32 +26,21 @@ namespace HybirdFrameworkCore.Autofac
throw new Exception(msg);
}
// AOP 开关,如果想要打开指定的功能,只需要在 appsettigns.json 对应对应 true 就行。
//var cacheType = new List<Type>();
//if (AppSettingsConstVars.RedisConfigEnabled)
//{
// builder.RegisterType<RedisCacheAop>();
// cacheType.Add(typeof(RedisCacheAop));
//}
//else
//{
// builder.RegisterType<MemoryCacheAop>();
// cacheType.Add(typeof(MemoryCacheAop));
//}
// 获取 Service.dll 程序集服务,并注册
SplitInject(Assembly.LoadFrom(servicesDllFile), builder);
// 获取 driver.dll 程序集服务,并注册
SplitInject(Assembly.LoadFrom(driverDllFile), builder);
// 获取 Repository.dll 程序集服务,并注册
SplitInject(Assembly.LoadFrom(repositoryDllFile), builder);
// 获取 Service.dll 程序集服务,并注册
SplitInject(Assembly.LoadFrom(servicesDllFile), builder);
#endregion
}
private void SplitInject(Assembly assemblysServices, ContainerBuilder builder)
{
List<Type> InstancePerLifetimeScopeList = new List<Type>();
List<Type> instancePerLifetimeScopeList = new List<Type>();
List<Type> instancePerDependencyList = new List<Type>();
List<Type> defaultList = new List<Type>();
foreach (var type in assemblysServices.ExportedTypes)
@ -60,21 +50,20 @@ namespace HybirdFrameworkCore.Autofac
{
if (ScopeConst.InstancePerLifetimeScope == scope.Scope)
{
InstancePerLifetimeScopeList.Add(type);
Log.Debug($"register InstancePerLifetimeScope {type}");
instancePerLifetimeScopeList.Add(type);
}
else if (ScopeConst.InstancePerDependency == scope.Scope)
{
Log.Debug($"register InstancePerDependency {type}");
instancePerDependencyList.Add(type);
}
else
{
Log.Debug($"register SingleInstance {type}");
defaultList.Add(type);
}
}
else
{
defaultList.Add(type);
}
}
if (defaultList.Count > 0)
@ -85,13 +74,46 @@ namespace HybirdFrameworkCore.Autofac
if (instancePerDependencyList.Count > 0)
{
builder.RegisterTypes(instancePerDependencyList.ToArray()).InstancePerDependency()
.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies); //支持属性注入依赖重复
foreach (Type type in instancePerDependencyList)
{
if (type.IsGenericType)
{
builder.RegisterGeneric(type).InstancePerDependency()
.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
}
else
{
Type? iInterface = type.GetInterface("HybirdFrameworkDriver.ChargerServer.IMsgHandler");
if (iInterface != null)
{
builder.RegisterType(type).As(iInterface).InstancePerDependency()
.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
}
iInterface = type.GetInterface("HybirdFrameworkDriver.ChargerServer.IDecoder");
if (iInterface != null)
{
builder.RegisterType(type).As(iInterface).InstancePerDependency()
.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
}
iInterface = type.GetInterface("HybirdFrameworkDriver.ChargerServer.IEncoder");
if (iInterface != null)
{
builder.RegisterType(type).As(iInterface).InstancePerDependency()
.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
}
builder.RegisterType(type).InstancePerDependency()
.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
}
}
}
if (InstancePerLifetimeScopeList.Count > 0)
if (instancePerLifetimeScopeList.Count > 0)
{
builder.RegisterTypes(InstancePerLifetimeScopeList.ToArray()).InstancePerMatchingLifetimeScope()
builder.RegisterTypes(instancePerLifetimeScopeList.ToArray()).InstancePerMatchingLifetimeScope()
.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies); //支持属性注入依赖重复
}
}

@ -1,7 +1,7 @@
using DotNetty.Common.Utilities;
using DotNetty.Transport.Channels;
namespace HybirdFrameworkServices.Netty;
namespace HybirdFrameworkDriver.ChargerServer;
public static class ChannelUtils
{

@ -0,0 +1,5 @@
namespace HybirdFrameworkDriver.ChargerServer;
public interface IDecoder
{
}

@ -0,0 +1,6 @@
namespace HybirdFrameworkDriver.ChargerServer;
public interface IEncoder
{
}

@ -0,0 +1,7 @@
using DotNetty.Transport.Channels;
namespace HybirdFrameworkDriver.ChargerServer;
public interface IMsgHandler
{
}

@ -2,7 +2,8 @@
using DotNetty.Transport.Channels;
using log4net;
namespace HybirdFrameworkServices.Netty;
namespace HybirdFrameworkDriver.ChargerServer;
public class IoSession
{

@ -1,18 +1,21 @@
using DotNetty.Buffers;
using System.Reflection;
using Autofac;
using DotNetty.Codecs;
using DotNetty.Handlers.Logging;
using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using HybirdFrameworkCore.Autofac;
using HybirdFrameworkCore.Autofac.Attribute;
using log4net;
namespace HybirdFrameworkServices.Netty
namespace HybirdFrameworkDriver.ChargerServer
{
/// <summary>
/// netty server
/// </summary>
[Scope("SingleInstance")]
[Scope("InstancePerDependency")]
public class Server : IDisposable
{
private readonly ILog Log = LogManager.GetLogger(typeof(Server));
@ -23,11 +26,8 @@ namespace HybirdFrameworkServices.Netty
private int _port = 9000;
public void connect(int port)
public Server()
{
_port = port;
IByteBuffer delimiter = Unpooled.CopiedBuffer(new byte[] { 0xAA, 0xF5 });
bossGroup = new MultithreadEventLoopGroup();
workerGroup = new MultithreadEventLoopGroup();
bootstrap = new ServerBootstrap();
@ -42,21 +42,48 @@ namespace HybirdFrameworkServices.Netty
IChannelPipeline pipeline = channel.Pipeline;
pipeline.AddLast(new LoggingHandler(""));
pipeline.AddLast(serverListenerHandler);
//pipeline.AddLast(new FixedLengthFrameDecoder(12)); //定长数据12byte
pipeline.AddLast(new IdleStateHandler(0, 0, 180));//检测空闲连接
//pipeline.AddLast(msgHandler);
//业务handler 这里是实际处理业务的Handler
pipeline.AddLast(new IdleStateHandler(0, 0, 180)); //检测空闲连接
//业务handler 这里是实际处理业务的Handler
pipeline.AddLast(new Decoder());
pipeline.AddLast(new Encoder());
pipeline.AddLast(new MsgHandler());
ResolveEncode(pipeline);
ResolveDecode(pipeline);
ResolveHandler(pipeline);
}));
Begin(_port);
}
private void ResolveEncode(IChannelPipeline pipeline)
{
IEncoder resolve = AppInfo.Container.Resolve<IEncoder>();
pipeline.AddLast((MessageToByteEncoder<byte[]>)resolve);
}
private void ResolveDecode(IChannelPipeline pipeline)
{
IDecoder resolve = AppInfo.Container.Resolve<IDecoder>();
pipeline.AddLast((ByteToMessageDecoder)resolve);
}
private void ResolveHandler(IChannelPipeline pipeline)
{
IEnumerable<IMsgHandler> handlers = AppInfo.Container.Resolve<IEnumerable<IMsgHandler>>();
IMsgHandler[] msgHandlers = handlers.ToArray();
Array.Sort(msgHandlers, (handler, msgHandler) =>
{
OrderAttribute? orderAttribute1 = handler.GetType().GetCustomAttribute<OrderAttribute>();
OrderAttribute? orderAttribute2 = msgHandler.GetType().GetCustomAttribute<OrderAttribute>();
int h1Order = orderAttribute1?.Order ?? 0;
int h2Order = orderAttribute2?.Order ?? 0;
return h1Order.CompareTo(h2Order);
});
foreach (var msgHandler in msgHandlers)
{
pipeline.AddLast((ChannelHandlerAdapter)msgHandler);
}
}
public void Begin(int port)
public void Start(int port)
{
_port = port;
Log.Info(" Start Listen");
@ -74,5 +101,4 @@ namespace HybirdFrameworkServices.Netty
bossGroup?.ShutdownGracefullyAsync();
}
}
}
}

@ -2,7 +2,8 @@
using HybirdFrameworkCore.Autofac.Attribute;
using log4net;
namespace HybirdFrameworkServices.Netty
namespace HybirdFrameworkDriver.ChargerServer
{
[Scope("InstancePerDependency")]
public class ServerListenerHandler : ChannelHandlerAdapter

@ -3,7 +3,7 @@ using DotNetty.Buffers;
using DotNetty.Transport.Channels;
using log4net;
namespace HybirdFrameworkServices.Netty;
namespace HybirdFrameworkDriver.ChargerServer;
public class SessionMgr
{
@ -15,7 +15,9 @@ public class SessionMgr
public static void RegisterSession(string key, IoSession ioSession)
{
ioSession.Key = key;
Dictionary.GetOrAdd(key, ioSession);
IoSession? session;
Dictionary.Remove(ioSession.Key, out session);
Dictionary.AddOrUpdate(key, ioSession, (k, oldSession) => ioSession);
}
public static void UnregisterSession(IChannel channel)

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="7.0.1" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="DotNetty.Buffers" Version="0.7.5" />
<PackageReference Include="DotNetty.Codecs" Version="0.7.5" />
<PackageReference Include="DotNetty.Codecs.Mqtt" Version="0.7.5" />
<PackageReference Include="DotNetty.Common" Version="0.7.5" />
<PackageReference Include="DotNetty.Handlers" Version="0.7.5" />
<PackageReference Include="DotNetty.Transport" Version="0.7.5" />
<PackageReference Include="log4net" Version="2.0.15" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HybirdFrameworkCore\HybirdFrameworkCore.csproj" />
</ItemGroup>
</Project>

@ -2,14 +2,15 @@
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkDriver.ChargerServer;
namespace HybirdFrameworkServices.Netty;
namespace HybirdFrameworkServices.Charger.Codec;
[Scope("InstancePerDependency")]
public class Decoder : ByteToMessageDecoder
public class Decoder : ByteToMessageDecoder, IDecoder
{
protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
{
throw new NotImplementedException();
output.Add(new IoSession(context.Channel));
}
}

@ -2,11 +2,12 @@
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkDriver.ChargerServer;
namespace HybirdFrameworkServices.Netty;
namespace HybirdFrameworkServices.Charger.Codec;
[Scope("InstancePerDependency")]
public class Encoder : MessageToByteEncoder<byte[]>
public class Encoder : MessageToByteEncoder<byte[]>, IEncoder
{
protected override void Encode(IChannelHandlerContext context, byte[] message, IByteBuffer output)
{

@ -0,0 +1,15 @@
using DotNetty.Transport.Channels;
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkDriver.ChargerServer;
using HybirdFrameworkServices.Charger.Msg;
namespace HybirdFrameworkServices.Charger.Handler;
[Order(9)]
[Scope("InstancePerDependency")]
public class Cmd106Handler : SimpleChannelInboundHandler<Cmd106>, IMsgHandler
{
protected override void ChannelRead0(IChannelHandlerContext ctx, Cmd106 msg)
{
}
}

@ -0,0 +1,14 @@
using DotNetty.Transport.Channels;
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkDriver.ChargerServer;
namespace HybirdFrameworkServices.Charger.Handler;
[Order(8)]
[Scope("InstancePerDependency")]
public class IoSessionHandler : SimpleChannelInboundHandler<IoSession>, IMsgHandler
{
protected override void ChannelRead0(IChannelHandlerContext ctx, IoSession msg)
{
}
}

@ -0,0 +1,9 @@
using HybirdFrameworkCore.Autofac.Attribute;
namespace HybirdFrameworkServices.Charger.Msg;
[Scope("InstancePerDependency")]
public class Cmd106
{
}

@ -19,6 +19,7 @@
<ItemGroup>
<ProjectReference Include="..\HybirdFrameworkCore\HybirdFrameworkCore.csproj" />
<ProjectReference Include="..\HybirdFrameworkDriver\HybirdFrameworkDriver.csproj" />
<ProjectReference Include="..\HybirdFrameworkEntity\HybirdFrameworkEntity.csproj" />
<ProjectReference Include="..\HybirdFrameworkRepository\HybirdFrameworkRepository.csproj" />
</ItemGroup>

@ -1,18 +0,0 @@
using DotNetty.Buffers;
using DotNetty.Transport.Channels;
using HybirdFrameworkCore.Autofac.Attribute;
using log4net;
namespace HybirdFrameworkServices.Netty;
[Scope("InstancePerDependency")]
public class MsgHandler : ChannelHandlerAdapter
{
private readonly ILog Log = LogManager.GetLogger(typeof(MsgHandler));
public override void ChannelRead(IChannelHandlerContext ctx, object msg)
{
Log.Info($"{this.GetHashCode()} read from {ctx.Channel.RemoteAddress}");
ctx.WriteAndFlushAsync(Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7 }));
}
}

@ -1,8 +0,0 @@
using Autofac;
namespace HybirdFrameworkServices.System;
public class AppInfo
{
public static IContainer Container { get; set; }
}

@ -1,9 +1,12 @@
using HybirdFrameworkEntity.DbModel;
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkEntity.DbModel;
using HybirdFrameworkRepository.System;
using HybirdFrameworkRepository.UnitOfWork;
namespace HybirdFrameworkServices.System
{
[Scope("SingleInstance")]
public class SysBatteryReplaceLogServices : BaseServices<sysBatteryReplaceLog>
{
SysBatteryReplaceLogRepository _dal;

@ -1,9 +1,11 @@
using HybirdFrameworkEntity.DbModel;
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkEntity.DbModel;
using HybirdFrameworkRepository.System;
using HybirdFrameworkRepository.UnitOfWork;
namespace HybirdFrameworkServices.System
{
[Scope("SingleInstance")]
public class SysDataSourceServices : BaseServices<sysDataSource>
{
private readonly SysDataSourceRepository _dal;

@ -1,8 +1,8 @@
using System.Text.Json;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using HybirdFrameworkCore.Autofac;
using HybirdFrameworkCore.Configuration;
using HybirdFrameworkDriver.ChargerServer;
using SqlSugar;
using SqlSugar.IOC;
@ -13,7 +13,6 @@ builder.Host.ConfigureContainer<ContainerBuilder>(cb =>
{
cb.Register(c =>
{
var db = new SqlSugarClient(new ConnectionConfig
{
ConfigId = AppSettingsConstVars.ConfigId,
@ -24,13 +23,11 @@ builder.Host.ConfigureContainer<ContainerBuilder>(cb =>
});
return db;
}).As<ISqlSugarClient>().InstancePerLifetimeScope();
cb.RegisterModule(new AutofacModuleRegister());
});
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
@ -39,6 +36,7 @@ builder.Logging.AddLog4Net("log4net.config");
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
@ -50,4 +48,9 @@ app.UseAuthorization();
app.MapControllers();
app.Run();
AppInfo.Container = app.Services.GetAutofacRoot();
Server server = AppInfo.Container.Resolve<Server>();
server.Start(9000);
app.Run();

@ -15,6 +15,7 @@
<ItemGroup>
<ProjectReference Include="..\HybirdFrameworkCore\HybirdFrameworkCore.csproj" />
<ProjectReference Include="..\HybirdFrameworkDriver\HybirdFrameworkDriver.csproj" />
<ProjectReference Include="..\HybirdFrameworkRepository\HybirdFrameworkRepository.csproj" />
<ProjectReference Include="..\HybirdFrameworkServices\HybirdFrameworkServices.csproj" />
</ItemGroup>

@ -1,9 +1,15 @@
namespace WinFormStarter;
using HybirdFrameworkDriver.ChargerServer;
namespace WinFormStarter;
public partial class Form2 : Form
{
public Form2()
private Server _server;
public Form2(Server server)
{
_server = server;
InitializeComponent();
_server.Start(9000);
}
}

@ -1,7 +1,6 @@
using Autofac;
using HybirdFrameworkCore.Autofac;
using HybirdFrameworkCore.Configuration;
using HybirdFrameworkServices.System;
using log4net.Config;
using SqlSugar;
using SqlSugar.IOC;
@ -50,8 +49,8 @@ static class Program
builder.RegisterModule(new AutofacModuleRegister());
// 构建容器
Container = builder.Build();
AppInfo.Container = Container;
Application.Run(Container.ResolveNamed<Form>("Form2"));
AppInfo.Container = Container.BeginLifetimeScope("root");
Application.Run(AppInfo.Container.ResolveNamed<Form>("Form2"));
}
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs ex)

@ -16,6 +16,7 @@
<ItemGroup>
<ProjectReference Include="..\HybirdFrameworkCore\HybirdFrameworkCore.csproj" />
<ProjectReference Include="..\HybirdFrameworkDriver\HybirdFrameworkDriver.csproj" />
<ProjectReference Include="..\HybirdFrameworkEntity\HybirdFrameworkEntity.csproj" />
<ProjectReference Include="..\HybirdFrameworkRepository\HybirdFrameworkRepository.csproj" />
<ProjectReference Include="..\HybirdFrameworkServices\HybirdFrameworkServices.csproj" />

@ -27,6 +27,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinFormStarter", "WinFormSt
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HybirdFrameworkEntity", "HybirdFrameworkEntity\HybirdFrameworkEntity.csproj", "{C2380814-15D4-491D-ADF2-ADC68617C3FA}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "HybirdFramework.Driver", "HybirdFramework.Driver", "{EF6B2DEC-ADAA-4A6D-AE93-0F98A555B265}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HybirdFrameworkDriver", "HybirdFrameworkDriver\HybirdFrameworkDriver.csproj", "{6ACFA707-E72E-4BA1-8262-9F2E5B758D46}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -57,6 +61,10 @@ Global
{C2380814-15D4-491D-ADF2-ADC68617C3FA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C2380814-15D4-491D-ADF2-ADC68617C3FA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C2380814-15D4-491D-ADF2-ADC68617C3FA}.Release|Any CPU.Build.0 = Release|Any CPU
{6ACFA707-E72E-4BA1-8262-9F2E5B758D46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6ACFA707-E72E-4BA1-8262-9F2E5B758D46}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6ACFA707-E72E-4BA1-8262-9F2E5B758D46}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6ACFA707-E72E-4BA1-8262-9F2E5B758D46}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -68,6 +76,7 @@ Global
{A6C2AA7F-B2A2-4AE0-AE84-49BE36B990EC} = {5F67ED42-6437-4FC6-86D2-0495DE990BC4}
{A6757DAD-EF5A-41FD-9323-F3FCF05ED777} = {A0BA21DB-6630-41AB-A0FD-594DBB197E0E}
{C2380814-15D4-491D-ADF2-ADC68617C3FA} = {6203689E-8261-4814-BFC2-013188AED6A1}
{6ACFA707-E72E-4BA1-8262-9F2E5B758D46} = {EF6B2DEC-ADAA-4A6D-AE93-0F98A555B265}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3E10BF3D-9914-44B1-A6AA-FCF013C3F155}

Loading…
Cancel
Save