From 5eb57995e84968b269ecb442d0d94b75064c852b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=B3=BD=E5=A8=81?= <1585955375@qq.com> Date: Thu, 20 Jul 2023 22:02:50 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat=20=EF=BC=9A=20=E6=B7=BB=E5=8A=A0Kafka?= =?UTF-8?q?=E6=B6=88=E6=81=AF=E6=80=BB=E7=BA=BF=EF=BC=8C=E7=B1=BB=E5=BA=93?= =?UTF-8?q?=E8=BF=98=E6=9C=AA=E5=AE=9E=E7=8E=B0=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Luck.sln | 7 ++++ .../Attributes/KafkaAttribute.cs | 34 +++++++++++++++++++ .../Luck.EventBus.Kafka.csproj | 13 +++++++ .../Luck.EventBus.Kafka/RabbitMqConfig.cs | 22 ++++++++++++ .../Luck.EventBus.Kafka/build_package.sh | 7 ++++ .../DefaultRabbitMQPersistentConnection.cs | 15 ++++---- test/Luck.UnitTest/KafkaTest.cs | 2 +- 7 files changed, 90 insertions(+), 10 deletions(-) create mode 100644 src/framework/Luck.EventBus.Kafka/Attributes/KafkaAttribute.cs create mode 100644 src/framework/Luck.EventBus.Kafka/Luck.EventBus.Kafka.csproj create mode 100644 src/framework/Luck.EventBus.Kafka/RabbitMqConfig.cs create mode 100755 src/framework/Luck.EventBus.Kafka/build_package.sh diff --git a/Luck.sln b/Luck.sln index 89b6b42..d7a347b 100644 --- a/Luck.sln +++ b/Luck.sln @@ -67,6 +67,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Luck.AppModule", "src\frame EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Luck.AutoDependencyInjection", "src\framework\Luck.AutoDependencyInjection\Luck.AutoDependencyInjection.csproj", "{404C5BB1-243A-4BB8-8FFF-740A2A5A1F5C}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Luck.EventBus.Kafka", "src\framework\Luck.EventBus.Kafka\Luck.EventBus.Kafka.csproj", "{9876D845-5C04-4B04-84A0-A57148253666}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -145,6 +147,10 @@ Global {404C5BB1-243A-4BB8-8FFF-740A2A5A1F5C}.Debug|Any CPU.Build.0 = Debug|Any CPU {404C5BB1-243A-4BB8-8FFF-740A2A5A1F5C}.Release|Any CPU.ActiveCfg = Release|Any CPU {404C5BB1-243A-4BB8-8FFF-740A2A5A1F5C}.Release|Any CPU.Build.0 = Release|Any CPU + {9876D845-5C04-4B04-84A0-A57148253666}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9876D845-5C04-4B04-84A0-A57148253666}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9876D845-5C04-4B04-84A0-A57148253666}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9876D845-5C04-4B04-84A0-A57148253666}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -176,6 +182,7 @@ Global {2893A93A-E580-4137-8229-BEB5EACA86E8} = {50FF08B1-264C-40B1-BA12-91A57B3C896D} {CD68536D-E0DF-44E0-9243-14E9A44DCF07} = {DE49CCE6-B41E-493A-ADCC-EA6075DD0038} {404C5BB1-243A-4BB8-8FFF-740A2A5A1F5C} = {DE49CCE6-B41E-493A-ADCC-EA6075DD0038} + {9876D845-5C04-4B04-84A0-A57148253666} = {5779CF18-7FD7-434D-B47A-1C8A50A3E5A4} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4719568B-E10A-4815-AAAA-8C6D6CEE798F} diff --git a/src/framework/Luck.EventBus.Kafka/Attributes/KafkaAttribute.cs b/src/framework/Luck.EventBus.Kafka/Attributes/KafkaAttribute.cs new file mode 100644 index 0000000..84c2303 --- /dev/null +++ b/src/framework/Luck.EventBus.Kafka/Attributes/KafkaAttribute.cs @@ -0,0 +1,34 @@ +using System.ComponentModel; +using Luck.Framework.Extensions; + +namespace Luck.EventBus.Kafka.Attributes +{ + /// + /// + /// + [AttributeUsage(AttributeTargets.Class)] + public class KafkaAttribute : Attribute + { + /// + /// + /// + /// 主题 + /// 标签 + public KafkaAttribute(string topic, string tag) + { + Topic = topic; + Tag = tag; + } + + /// + /// 主题 + /// + public string Topic { get; private set; } + + /// + /// 标签 + /// + public string Tag { get; private set; } + + } +} \ No newline at end of file diff --git a/src/framework/Luck.EventBus.Kafka/Luck.EventBus.Kafka.csproj b/src/framework/Luck.EventBus.Kafka/Luck.EventBus.Kafka.csproj new file mode 100644 index 0000000..a091a85 --- /dev/null +++ b/src/framework/Luck.EventBus.Kafka/Luck.EventBus.Kafka.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/src/framework/Luck.EventBus.Kafka/RabbitMqConfig.cs b/src/framework/Luck.EventBus.Kafka/RabbitMqConfig.cs new file mode 100644 index 0000000..774c4c8 --- /dev/null +++ b/src/framework/Luck.EventBus.Kafka/RabbitMqConfig.cs @@ -0,0 +1,22 @@ +namespace Luck.EventBus.Kafka +{ + public class KafkaMqConfig + { + + + + public const int UseDefaultPort = 9092; + + + public string Host { get; set; } = default!; + + public string PassWord { get; set; } = default!; + + public string UserName { get; set; } = default!; + + public int RetryCount { get; set; } = default!; + + public int Port { get; set; } = UseDefaultPort; + + } +} \ No newline at end of file diff --git a/src/framework/Luck.EventBus.Kafka/build_package.sh b/src/framework/Luck.EventBus.Kafka/build_package.sh new file mode 100755 index 0000000..27f38bc --- /dev/null +++ b/src/framework/Luck.EventBus.Kafka/build_package.sh @@ -0,0 +1,7 @@ +#!/bin/bash +echo "请输入NUGET_API_KEY" +read NUGET_API_KEY +rm bin/Release/*.nupkg +dotnet build -c Release +dotnet pack -c Release +dotnet nuget push bin/Release/*.nupkg -k $NUGET_API_KEY -s https://api.nuget.org/v3/index.json \ No newline at end of file diff --git a/src/framework/Luck.EventBus.RabbitMQ/DefaultRabbitMQPersistentConnection.cs b/src/framework/Luck.EventBus.RabbitMQ/DefaultRabbitMQPersistentConnection.cs index 7603bcd..829c22e 100644 --- a/src/framework/Luck.EventBus.RabbitMQ/DefaultRabbitMQPersistentConnection.cs +++ b/src/framework/Luck.EventBus.RabbitMQ/DefaultRabbitMQPersistentConnection.cs @@ -17,13 +17,13 @@ public class DefaultRabbitMqPersistentConnection private readonly IConnectionFactory _connectionFactory; private readonly ILogger _logger; private readonly int _retryCount; - IConnection? _connection; - bool _disposed; + private IConnection? _connection; + private bool _disposed; /// /// /// - object sync_root = new object(); + private readonly object _syncRoot = new object(); public DefaultRabbitMqPersistentConnection(IConnectionFactory connectionFactory, ILogger logger, int retryCount = 5) @@ -34,10 +34,7 @@ public DefaultRabbitMqPersistentConnection(IConnectionFactory connectionFactory, } - public bool IsConnected - { - get { return _connection != null && _connection.IsOpen && !_disposed; } - } + public bool IsConnected => _connection is { IsOpen: true } && !_disposed; public IModel CreateModel() { @@ -76,9 +73,9 @@ public bool TryConnect() { _logger.LogInformation("RabbitMQ客户端尝试连接"); - lock (sync_root) + lock (_syncRoot) { - var policy = RetryPolicy.Handle() + var policy = Policy.Handle() .Or() .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => { _logger.LogWarning(ex, "RabbitMQ客户端无法连接 {TimeOut}s ({ExceptionMessage})", $"{time.TotalSeconds:n1}", ex.Message); } ); diff --git a/test/Luck.UnitTest/KafkaTest.cs b/test/Luck.UnitTest/KafkaTest.cs index d594a3e..69e6c0f 100644 --- a/test/Luck.UnitTest/KafkaTest.cs +++ b/test/Luck.UnitTest/KafkaTest.cs @@ -11,7 +11,7 @@ public class KafkaTest [Fact] public async Task Kafka_Connect_Test() { - var config = new ProducerConfig { BootstrapServers = "192.168.31.11:30115" }; + var config = new ProducerConfig { BootstrapServers = "192.168.31.11:30115",Acks =Acks.All }; try { using (var p = new ProducerBuilder(config).Build()) From 1e1c59e2b41da55652f3ec1e24f7e1a36f8d8fd2 Mon Sep 17 00:00:00 2001 From: dong <44517714+lurudong@users.noreply.github.com> Date: Mon, 31 Jul 2023 19:44:57 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=B1=9E=E6=80=A7?= =?UTF-8?q?=E6=B3=A8=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/TestsController.cs | 25 +++--- sample/Module.Sample/Program.cs | 13 ++-- sample/Module.Sample/Services/OrderService.cs | 21 ++--- .../IPropertyInjectionServiceProvider.cs | 13 ++++ .../Abstractions/IPropertyInjector.cs | 16 ++++ .../Luck.AutoDependencyInjection.csproj | 4 + .../PropertyInjectionControllerFactory.cs | 41 ++++++++++ .../PropertyInjectionServiceProvider.cs | 40 ++++++++++ ...PropertyInjectionServiceProviderFactory.cs | 33 ++++++++ .../PropertyInjector.cs} | 78 +++++++++---------- .../ServiceCollectionExtension.cs | 27 +++++++ .../PropertyInjectionExtension.cs | 17 ---- ...PropertyInjectionServiceProviderFactory.cs | 23 ------ 13 files changed, 237 insertions(+), 114 deletions(-) create mode 100644 src/framework/Luck.AutoDependencyInjection/Abstractions/IPropertyInjectionServiceProvider.cs create mode 100644 src/framework/Luck.AutoDependencyInjection/Abstractions/IPropertyInjector.cs create mode 100644 src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjectionControllerFactory.cs create mode 100644 src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjectionServiceProvider.cs create mode 100644 src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjectionServiceProviderFactory.cs rename src/framework/Luck.AutoDependencyInjection/{PropertyInjectionServiceProvider.cs => PropertyInjection/PropertyInjector.cs} (51%) create mode 100644 src/framework/Luck.AutoDependencyInjection/PropertyInjection/ServiceCollectionExtension.cs delete mode 100644 src/framework/Luck.AutoDependencyInjection/PropertyInjectionExtension.cs delete mode 100644 src/framework/Luck.AutoDependencyInjection/PropertyInjectionServiceProviderFactory.cs diff --git a/sample/Module.Sample/Controllers/TestsController.cs b/sample/Module.Sample/Controllers/TestsController.cs index 6aad208..bbcdade 100644 --- a/sample/Module.Sample/Controllers/TestsController.cs +++ b/sample/Module.Sample/Controllers/TestsController.cs @@ -1,5 +1,5 @@ -using Luck.Framework.Extensions; -using Microsoft.AspNetCore.Http; +using Luck.AutoDependencyInjection.Attributes; +using Luck.Framework.Extensions; using Microsoft.AspNetCore.Mvc; using Module.Sample.Services; using System.ComponentModel; @@ -11,32 +11,33 @@ namespace Module.Sample.Controllers public class TestsController : ControllerBase { + [Injection] private readonly IOrderService _orderService; - public TestsController(IOrderService orderService) - { - _orderService = orderService; - } + //public TestsController(IOrderService orderService) + //{ + // _orderService = orderService; + //} [HttpGet] public Task TestEnumToList() { - var list= typeof(TestEnum).TypeToEnumList(); - - return Task.FromResult(list); + var list = typeof(TestEnum).TypeToEnumList(); + + return Task.FromResult(list); } [HttpPost] - public Task CreateAndEventAsync() + public Task CreateAndEventAsync() { return _orderService.CreateAndEventAsync(); } - + [HttpPost] - public Task CreateOrder() + public Task CreateOrder() { return _orderService.CreateAndEventAsync(); diff --git a/sample/Module.Sample/Program.cs b/sample/Module.Sample/Program.cs index 127f9f9..5598432 100644 --- a/sample/Module.Sample/Program.cs +++ b/sample/Module.Sample/Program.cs @@ -1,9 +1,7 @@ -using System.Diagnostics; -using Luck.Framework.Infrastructure; -using MediatR; -using Module.Sample; using Luck.AppModule; -using Luck.AutoDependencyInjection; +using Luck.AutoDependencyInjection.PropertyInjection; +using Module.Sample; +using System.Diagnostics; var builder = WebApplication.CreateBuilder(args); @@ -15,8 +13,11 @@ builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddHttpContextAccessor(); + +// +builder.Host.UsePropertyInjection(); // builder.Services.AddDoveLogger(); -builder.Host.UseDefaultPropertyInjection(); + var app = builder.Build(); diff --git a/sample/Module.Sample/Services/OrderService.cs b/sample/Module.Sample/Services/OrderService.cs index 6e00bb9..3faef62 100644 --- a/sample/Module.Sample/Services/OrderService.cs +++ b/sample/Module.Sample/Services/OrderService.cs @@ -1,10 +1,7 @@ using Luck.AutoDependencyInjection.Attributes; using Luck.DDD.Domain.Repositories; -using Luck.Framework.Extensions; -using Luck.Framework.Infrastructure.Caching; using Luck.Framework.Infrastructure.DependencyInjectionModule; using Luck.Framework.UnitOfWorks; -using MediatR; using Microsoft.EntityFrameworkCore; using Module.Sample.Domain; using Module.Sample.EventHandlers; @@ -14,20 +11,14 @@ namespace Module.Sample.Services public class OrderService : IOrderService { + [Injection] private readonly IAggregateRootRepository _aggregateRootRepository; - //[Injection] + [Injection] private readonly IUnitOfWork _unitOfWork; - private readonly IMediator _mediator; - public OrderService(IAggregateRootRepository aggregateRootRepository - , IUnitOfWork unitOfWork - //, IMediator mediator - ) - { - _aggregateRootRepository = aggregateRootRepository; - _unitOfWork = unitOfWork; - //_mediator = mediator; - } + + [Injection] + private readonly ILogger _logger; public async Task CreateAsync() { @@ -35,6 +26,7 @@ public async Task CreateAsync() order.SetOrderItem(); _aggregateRootRepository.Add(order); + _logger?.LogInformation("调用了CreateAsync()方法"); await _unitOfWork.CommitAsync(); } @@ -48,6 +40,7 @@ public async Task CreateAndEventAsync() var order = new Order("asdasdsa", "asdasdadas"); _aggregateRootRepository.Add(order); order.AddDomainEvent(new OrderCreatedEto() { Id = order.Id, Name = order.Name }); + _logger?.LogInformation("调用了CreateAndEventAsync()方法"); await _unitOfWork.CommitAsync(); //await _cache.AddAsync("order_a1", order); //var test=await _cache.GetAsync("order_a1"); diff --git a/src/framework/Luck.AutoDependencyInjection/Abstractions/IPropertyInjectionServiceProvider.cs b/src/framework/Luck.AutoDependencyInjection/Abstractions/IPropertyInjectionServiceProvider.cs new file mode 100644 index 0000000..47f2ff6 --- /dev/null +++ b/src/framework/Luck.AutoDependencyInjection/Abstractions/IPropertyInjectionServiceProvider.cs @@ -0,0 +1,13 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace Luck.AutoDependencyInjection.Abstractions +{ + + /// + /// 属性注入提供者接口 + /// + public interface IPropertyInjectionServiceProvider : IServiceProvider, ISupportRequiredService + { + + } +} diff --git a/src/framework/Luck.AutoDependencyInjection/Abstractions/IPropertyInjector.cs b/src/framework/Luck.AutoDependencyInjection/Abstractions/IPropertyInjector.cs new file mode 100644 index 0000000..995e589 --- /dev/null +++ b/src/framework/Luck.AutoDependencyInjection/Abstractions/IPropertyInjector.cs @@ -0,0 +1,16 @@ +namespace Luck.AutoDependencyInjection.Abstractions +{ + + /// + /// 属性注入接口 + /// + internal interface IPropertyInjector + { + /// + /// 注入属性 + /// + /// 要注入的实例 + /// + object InjectProperties(object instance); + } +} diff --git a/src/framework/Luck.AutoDependencyInjection/Luck.AutoDependencyInjection.csproj b/src/framework/Luck.AutoDependencyInjection/Luck.AutoDependencyInjection.csproj index ccf47ea..979fefd 100644 --- a/src/framework/Luck.AutoDependencyInjection/Luck.AutoDependencyInjection.csproj +++ b/src/framework/Luck.AutoDependencyInjection/Luck.AutoDependencyInjection.csproj @@ -6,6 +6,10 @@ enable + + + + diff --git a/src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjectionControllerFactory.cs b/src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjectionControllerFactory.cs new file mode 100644 index 0000000..b4a2f19 --- /dev/null +++ b/src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjectionControllerFactory.cs @@ -0,0 +1,41 @@ +using Luck.AutoDependencyInjection.Abstractions; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Controllers; + +namespace Luck.AutoDependencyInjection.PropertyInjection +{ + /// + /// 属性注入控制器我工厂,用来创建控制器,激活控制器 + /// + internal class PropertyInjectionControllerFactory : IControllerFactory + { + private readonly IPropertyInjector _propertyInjector; + private readonly IControllerActivator _controllerActivator; + + /// + /// + /// + /// + /// + public PropertyInjectionControllerFactory(IPropertyInjector propertyInjector, IControllerActivator controllerActivator) + { + _propertyInjector = propertyInjector; + _controllerActivator = controllerActivator; + } + + /// + /// 创建控制器 + /// + /// + /// + public object CreateController(ControllerContext context) => _propertyInjector.InjectProperties(_controllerActivator.Create(context)); + + + /// + /// 替换控制器 + /// + /// + /// + public void ReleaseController(ControllerContext context, object controller) => _controllerActivator.Release(context, controller); + } +} diff --git a/src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjectionServiceProvider.cs b/src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjectionServiceProvider.cs new file mode 100644 index 0000000..cbccfe6 --- /dev/null +++ b/src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjectionServiceProvider.cs @@ -0,0 +1,40 @@ +using Luck.AutoDependencyInjection.Abstractions; +using Microsoft.Extensions.DependencyInjection; + +namespace Luck.AutoDependencyInjection.PropertyInjection +{ + /// + /// 属性注入提供者接口 + /// + internal class PropertyInjectionServiceProvider : IPropertyInjectionServiceProvider + { + private readonly IPropertyInjector _propertyInjector; + private readonly IServiceProvider _serviceProvider; + + /// + /// + /// + /// + public PropertyInjectionServiceProvider(IServiceCollection service) + { + ArgumentNullException.ThrowIfNull(service, nameof(service)); + service.AddSingleton(this); + _serviceProvider = service.BuildServiceProvider(); + _propertyInjector = new PropertyInjector(this); + } + + + + public object? GetService(Type serviceType) + { + var instance = _serviceProvider.GetService(serviceType); + return instance is null ? null : _propertyInjector.InjectProperties(instance); + } + + public object GetRequiredService(Type serviceType) + { + var service = GetService(serviceType); + return service; + } + } +} diff --git a/src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjectionServiceProviderFactory.cs b/src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjectionServiceProviderFactory.cs new file mode 100644 index 0000000..5e026f2 --- /dev/null +++ b/src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjectionServiceProviderFactory.cs @@ -0,0 +1,33 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace Luck.AutoDependencyInjection.PropertyInjection +{ + /// + /// 属性注入服务提供者工厂 + /// + internal class PropertyInjectionServiceProviderFactory : IServiceProviderFactory + { + /// + /// 创建服务提供者 + /// + /// 容器建造者 + /// + public IServiceProvider CreateServiceProvider(IServiceCollection containerBuilder) + { + return new PropertyInjectionServiceProvider(containerBuilder); + } + + /// + /// 创建构建器 + /// + /// 服务集合 + /// + + public IServiceCollection CreateBuilder(IServiceCollection? services) + { + + return services ?? new ServiceCollection(); + } + + } +} diff --git a/src/framework/Luck.AutoDependencyInjection/PropertyInjectionServiceProvider.cs b/src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjector.cs similarity index 51% rename from src/framework/Luck.AutoDependencyInjection/PropertyInjectionServiceProvider.cs rename to src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjector.cs index 0486010..89d5ee5 100644 --- a/src/framework/Luck.AutoDependencyInjection/PropertyInjectionServiceProvider.cs +++ b/src/framework/Luck.AutoDependencyInjection/PropertyInjection/PropertyInjector.cs @@ -1,69 +1,55 @@ -using Luck.Framework.Extensions; +using Luck.AutoDependencyInjection.Abstractions; using Luck.AutoDependencyInjection.Attributes; +using Luck.Framework.Extensions; using System.Reflection; -using Luck.Framework.Infrastructure.DependencyInjectionPropertyInjection; -namespace Luck.AutoDependencyInjection +namespace Luck.AutoDependencyInjection.PropertyInjection { - /// - /// 属性注入提供者 + /// 属性注入注射器类 /// - public class PropertyInjectionServiceProvider : IPropertyInjectionServiceProvider + /// + internal sealed class PropertyInjector : IPropertyInjector + { + private readonly IPropertyInjectionServiceProvider _provider; - private readonly IServiceProvider _serviceProvider; - /// - /// - /// - /// - /// - public PropertyInjectionServiceProvider(IServiceProvider serviceProvider) + public PropertyInjector(IPropertyInjectionServiceProvider provider) { - _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); + _provider = provider; } - - private static BindingFlags BindingFlags => BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; + /// - /// 得到服务 + /// 注入的属性 /// - /// + /// 实例 /// - /// - public object GetService(Type serviceType) + public object InjectProperties(object instance) { - var instance = _serviceProvider.GetService(serviceType); IsInjectProperties(instance); - return instance!; + return instance; } /// - /// 得到所需服务 - /// - /// - /// - /// - public object GetRequiredService(Type serviceType) => GetService(serviceType); - - /// - /// 判断注入属性 + /// 判断是否需要属性注入 /// /// - public void IsInjectProperties(object? instance) + private void IsInjectProperties(object? instance) { if (instance is null) return; var type = instance as Type ?? instance.GetType(); + //找到所有需要注入的成员,进行注入 type.GetMembers(BindingFlags).Where(o => o.HasAttribute()).ToList().ForEach(member => InjectMember(instance, member)); } /// - /// 成员 + /// 需要注入的成员(属性或字段) /// - /// - /// + /// 实例 + /// 成员信息 private void InjectMember(object instance, MemberInfo member) { if (member.MemberType == MemberTypes.Property) @@ -75,10 +61,10 @@ private void InjectMember(object instance, MemberInfo member) } /// - /// 属性 + /// 属性注入 /// - /// - /// + /// 实例 + /// 属性信息 private void InjectProperty(object instance, PropertyInfo prop) { if (prop.CanWrite) @@ -88,10 +74,18 @@ private void InjectProperty(object instance, PropertyInfo prop) } /// - /// 字段 + /// 字段注入 /// - /// - /// + /// 实例 + /// 字段信息 private void InjectField(object instance, FieldInfo field) => field.SetValue(instance, GetService(field.FieldType)); + + /// + /// 获取服务 + /// + /// + /// + /// + private object GetService(Type type) => _provider.GetService(type) ?? throw new NullReferenceException($"找不到类型服务 {type.Name}"); } -} \ No newline at end of file +} diff --git a/src/framework/Luck.AutoDependencyInjection/PropertyInjection/ServiceCollectionExtension.cs b/src/framework/Luck.AutoDependencyInjection/PropertyInjection/ServiceCollectionExtension.cs new file mode 100644 index 0000000..62a76a5 --- /dev/null +++ b/src/framework/Luck.AutoDependencyInjection/PropertyInjection/ServiceCollectionExtension.cs @@ -0,0 +1,27 @@ +using Luck.AutoDependencyInjection.Abstractions; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Luck.AutoDependencyInjection.PropertyInjection +{ + public static class ServiceCollectionExtension + { + /// + /// 使用属性注入 + /// + /// host构建器 + /// + public static void UsePropertyInjection(this IHostBuilder hostBuilder) + { + hostBuilder.UseServiceProviderFactory(new PropertyInjectionServiceProviderFactory()).ConfigureServices(ConfigureServices); + } + + private static void ConfigureServices(IServiceCollection services) + { + services. + AddSingleton() + .AddSingleton(); + } + } +} diff --git a/src/framework/Luck.AutoDependencyInjection/PropertyInjectionExtension.cs b/src/framework/Luck.AutoDependencyInjection/PropertyInjectionExtension.cs deleted file mode 100644 index 5a2c691..0000000 --- a/src/framework/Luck.AutoDependencyInjection/PropertyInjectionExtension.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.Extensions.Hosting; - -namespace Luck.AutoDependencyInjection -{ - /// - /// 属性注入扩展 - /// - public static class PropertyInjectionExtension - { - /// - /// 使用属性注入 - /// - /// - /// - public static void UseDefaultPropertyInjection(this IHostBuilder hostBuilder) => hostBuilder.UseServiceProviderFactory(new PropertyInjectionServiceProviderFactory()); - } -} diff --git a/src/framework/Luck.AutoDependencyInjection/PropertyInjectionServiceProviderFactory.cs b/src/framework/Luck.AutoDependencyInjection/PropertyInjectionServiceProviderFactory.cs deleted file mode 100644 index f086fef..0000000 --- a/src/framework/Luck.AutoDependencyInjection/PropertyInjectionServiceProviderFactory.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; - -namespace Luck.AutoDependencyInjection -{ - - /// - /// 属性注入服务提供者工厂 - /// - public class PropertyInjectionServiceProviderFactory : IServiceProviderFactory - { - /// - /// - /// - /// - public IServiceProvider CreateServiceProvider(IServiceCollection containerBuilder) - { - var serviceProvider = containerBuilder.BuildServiceProvider(); - return new PropertyInjectionServiceProvider(serviceProvider); - } - - IServiceCollection IServiceProviderFactory.CreateBuilder(IServiceCollection? services) => services ?? new ServiceCollection(); - } -}