├── XUnitTest ├── UnitTest.cs └── XUnitTest.csproj ├── Message ├── Message.csproj ├── AbstractEvent.cs └── OrderCreatedEvent.cs ├── Consumer ├── appsettings.Development.json ├── MongoDbEntity │ ├── GuidEventLog.cs │ ├── CommonEventLog.cs │ └── EventLogBase.cs ├── Option │ └── MongoConfig.cs ├── AutoMapper │ ├── OrderCreatedEventProfile.cs │ └── AutoMapperExtension.cs ├── Mongo │ └── MongoDbContext.cs ├── appsettings.json ├── Program.cs ├── Properties │ └── launchSettings.json ├── EventConsumer │ ├── EasyNetQConsumerBase.cs │ └── OrderCreatedEventConsumer.cs ├── Controllers │ └── ValuesController.cs ├── Consumer.csproj ├── EasyNetQ │ ├── ConsumerMessageDispatcher.cs │ └── EasyNetQExtension.cs ├── Startup.cs └── log4net.config ├── Productor ├── Common │ ├── Check.cs │ ├── IEventBus.cs │ ├── KnownException.cs │ ├── ApiResult.cs │ └── RabbitMqEventBus.cs ├── appsettings.Development.json ├── AutoMapper │ ├── BaseProfile.cs │ └── OrderProfile.cs ├── Config │ └── RedisConfig.cs ├── Quartz │ ├── IgnoreJobAttribute.cs │ ├── JobDescriptionAttribute.cs │ ├── TestHelloJob.cs │ ├── ClearHistoryMessageJob.cs │ ├── JobIntervalTriggerAttribute.cs │ ├── JobBase.cs │ ├── ProductorJobFactory.cs │ ├── PublishToMqServerJob.cs │ └── QuartzExtension.cs ├── Service │ ├── IOrderService.cs │ └── OrderService.cs ├── Data │ ├── Entity.cs │ ├── OrderHeader.cs │ ├── OrderDetail.cs │ ├── MqMessage.cs │ ├── EntityTypeMapConfig │ │ ├── OrderHeaderMapConfig.cs │ │ ├── MqMessageTypeConfig.cs │ │ └── OrderDetailMapConfig.cs │ └── ProductDbContext.cs ├── Hangfire │ └── HangfireExtension.cs ├── Interceptor │ ├── TestDebugIAspectCorenterceptorAttribute.cs │ ├── LogExceptionAspectCoreInterceptorAttribute.cs │ ├── LogExceptionCastleInterceptor.cs │ ├── CacheAspectCoreInterceptorAttribute.cs │ └── RedisCacheAspectCoreInterceptorAttribute.cs ├── appsettings.json ├── Program.cs ├── Migrations │ ├── 20180414032731_AddColumnToMqMessage.cs │ ├── 20180414013731_SettingDeciaml.cs │ ├── 20180413034406_UpdateOrderConfig.cs │ ├── 20180412155138_InitProductDb.cs │ ├── 20180413034406_UpdateOrderConfig.Designer.cs │ ├── 20180414013731_SettingDeciaml.Designer.cs │ ├── 20180412155138_InitProductDb.Designer.cs │ ├── ProductDbContextModelSnapshot.cs │ └── 20180414032731_AddColumnToMqMessage.Designer.cs ├── Properties │ └── launchSettings.json ├── EventConsumer │ └── EasyNetQConsumerBase.cs ├── Controllers │ ├── ControllerBase.cs │ ├── ValuesController.cs │ └── OrderController.cs ├── Model │ ├── OrderInput.cs │ └── OrderOutput.cs ├── Filter │ ├── ValidateModelStateAttribute.cs │ ├── GlobalExceptionFilter.cs │ └── ExceptionActionFilter.cs ├── EasyNetQ │ ├── ProductorMessageDispatcher.cs │ └── EasyNetQExtension.cs ├── Swagger │ └── SwaggerExtension.cs ├── Productor.csproj ├── Startup.cs └── log4net.config ├── readme.txt ├── .gitattributes ├── LocalTransactionTableTest.sln └── .gitignore /XUnitTest/UnitTest.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Inuyasha-Monster/LocalTransactionTableTest/HEAD/XUnitTest/UnitTest.cs -------------------------------------------------------------------------------- /Message/Message.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.0 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Consumer/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "LogLevel": { 5 | "Default": "Debug", 6 | "System": "Information", 7 | "Microsoft": "Information" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Productor/Common/Check.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Productor.Common 7 | { 8 | public static class Check 9 | { 10 | 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Productor/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "LogLevel": { 5 | "Default": "Debug", 6 | "System": "Information", 7 | "Microsoft": "Information" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Consumer/MongoDbEntity/GuidEventLog.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Consumer.MongoDbEntity 7 | { 8 | public class GuidEventLog : CommonEventLog 9 | { 10 | 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Consumer/Option/MongoConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Consumer.Option 7 | { 8 | public class MongoConfig 9 | { 10 | public string ConnectionString { get; set; } 11 | public string Database { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Productor/AutoMapper/BaseProfile.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AutoMapper; 6 | 7 | namespace Productor.AutoMapper 8 | { 9 | public class BaseProfile : Profile 10 | { 11 | public BaseProfile() 12 | { 13 | 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Productor/Config/RedisConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Productor.Config 7 | { 8 | public class RedisConfig 9 | { 10 | public string Configuration { get; set; } 11 | public string InstanceName { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Productor/Quartz/IgnoreJobAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Productor.Quartz 7 | { 8 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] 9 | public class IgnoreJobAttribute : Attribute 10 | { 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Productor/Service/IOrderService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Productor.Interceptor; 3 | using Productor.Model; 4 | 5 | namespace Productor.Service 6 | { 7 | public interface IOrderService 8 | { 9 | //[CacheAspectCoreInterceptor] 10 | [RedisCacheAspectCoreInterceptor] 11 | OrderOutput GetOrderInfo(Guid id); 12 | 13 | void CreateOrder(OrderInput input); 14 | } 15 | } -------------------------------------------------------------------------------- /Message/AbstractEvent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Message 6 | { 7 | public abstract class AbstractEvent 8 | { 9 | protected AbstractEvent() 10 | { 11 | EventId = Guid.NewGuid(); 12 | EventUtcTime = DateTime.UtcNow; 13 | } 14 | public Guid EventId { get; set; } 15 | public DateTime EventUtcTime { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Productor/Common/IEventBus.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Productor.Common 7 | { 8 | public interface IEventBus 9 | { 10 | void Publish(T message) where T : class, new(); 11 | Task PublishAsync(T message) where T : class, new(); 12 | 13 | void Publish(Type messageType, object message); 14 | void PublishAsync(Type messageType, object message); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Productor/Data/Entity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Productor.Data 7 | { 8 | public class Entity where TPk : struct 9 | { 10 | public TPk Id { get; set; } 11 | } 12 | 13 | public class EntityGuid : Entity 14 | { 15 | 16 | } 17 | 18 | public class EntityGuidBaseField : EntityGuid 19 | { 20 | public DateTime CreateTime { get; set; } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Productor/Common/KnownException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Productor.Common 7 | { 8 | public class KnownException : Exception 9 | { 10 | public KnownException(string message) : base(message) 11 | { 12 | 13 | } 14 | 15 | public KnownException(string message, Exception innerException) : base(message, innerException) 16 | { 17 | 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Productor/Quartz/JobDescriptionAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Productor.Quartz 7 | { 8 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] 9 | public class JobDescriptionAttribute : Attribute 10 | { 11 | public string Key { get; set; } 12 | public string Group { get; set; } 13 | public string Description { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Consumer/MongoDbEntity/CommonEventLog.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Consumer.MongoDbEntity 7 | { 8 | public class CommonEventLog : EventLogBase 9 | { 10 | public string MessageAssemblyName { get; set; } 11 | public string MessageClassFullName { get; set; } 12 | public string Body { get; set; } 13 | public T DatabaseId { get; set; } 14 | public DateTime CreateTime { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Consumer/AutoMapper/OrderCreatedEventProfile.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AutoMapper; 6 | using Consumer.MongoDbEntity; 7 | using Message; 8 | 9 | namespace Consumer.AutoMapper 10 | { 11 | public class OrderCreatedEventProfile : Profile 12 | { 13 | public OrderCreatedEventProfile() 14 | { 15 | this.CreateMap().ForMember(d => d.DatabaseId, s => s.MapFrom(soucre => soucre.Id)); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Productor/Data/OrderHeader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Productor.Data 7 | { 8 | public class OrderHeader 9 | { 10 | public OrderHeader() 11 | { 12 | Id = Guid.NewGuid(); 13 | CreateTime = DateTime.Now; 14 | } 15 | public Guid Id { get; set; } 16 | public decimal Amount { get; set; } 17 | public DateTime CreateTime { get; set; } 18 | public string AppUser { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | todo: 2 | 1、实现serivce方法拦截:Cache应用 --ok 3 | 4 | 2、代码整理分离 迁移到 YiXinFramework --working 5 | 6 | 3、实现 Polly 重试容错处理 --ok 集成消息推送rabbitmqserver容错与消费者消费mq重试 Update: 将 Polly 重试机制迁移到 interceptor 当中去作为公共逻辑 7 | 8 | 4、实现发送消息错误报警接口设计(打算先实现邮件提醒) 9 | 10 | 5、集成分布式缓存 --ok (redis) 11 | 6、启用消费者负载均衡 12 | 7、启用rabbitmq集群模式测试 13 | 8、集成服务发现和治理(多个生产者均衡负载,但是数据库目前是同一个的模式) 14 | 9、集成quartz-ui管理界面 15 | 10、集成hangfire-RAM内存模式测试 16 | 11、集成kafka消息队列测试 17 | 12、关于解析 dbmessage 通过 eventbus 发送,做反射优化以及缓存提升性能 18 | 13、独立出来一个 MessageDbContext 发布nuget package方便使用,在使用migration迁移即可 19 | 14、集成 ExceptionLess / ELK 日志集中式处理 20 | -------------------------------------------------------------------------------- /Productor/Hangfire/HangfireExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.Extensions.DependencyInjection; 7 | 8 | namespace Productor.Hangfire 9 | { 10 | public static class HangfireExtension 11 | { 12 | public static void AddHangfire(this IServiceCollection service, string connection) 13 | { 14 | 15 | } 16 | 17 | public static void UseHangfire(this IApplicationBuilder app) 18 | { 19 | 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Consumer/MongoDbEntity/EventLogBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using MongoDB.Bson; 6 | using MongoDB.Bson.Serialization.Attributes; 7 | 8 | namespace Consumer.MongoDbEntity 9 | { 10 | public abstract class EventLogBase 11 | { 12 | [BsonId] 13 | // standard BSonId generated by MongoDb 14 | public ObjectId InternalId { get; set; } 15 | 16 | // external ID or key, which may be easier to reference (ex: 1,2,3 etc.) 17 | public Guid EventId { get; set; } 18 | 19 | public DateTime EventUtcTime { get; set; } 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Productor/Interceptor/TestDebugIAspectCorenterceptorAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using AspectCore.DynamicProxy; 7 | 8 | namespace Productor.Interceptor 9 | { 10 | public class TestDebugIAspectCorenterceptorAttribute : AbstractInterceptorAttribute 11 | { 12 | public override async Task Invoke(AspectContext context, AspectDelegate next) 13 | { 14 | Debug.WriteLine("Before service call"); 15 | await next(context); 16 | Debug.WriteLine("After service call"); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Productor/Data/OrderDetail.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Productor.Data 7 | { 8 | public class OrderDetail 9 | { 10 | public OrderDetail() 11 | { 12 | Id = Guid.NewGuid(); 13 | CreateTime = DateTime.Now; 14 | } 15 | public Guid Id { get; set; } 16 | public Guid ParentId { get; set; } 17 | public string Sku { get; set; } 18 | public string SkuName { get; set; } 19 | public int Quantity { get; set; } 20 | public decimal Price { get; set; } 21 | public DateTime CreateTime { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Productor/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "Debug": { 5 | "LogLevel": { 6 | "Default": "Warning" 7 | } 8 | }, 9 | "Console": { 10 | "LogLevel": { 11 | "Default": "Warning" 12 | } 13 | } 14 | }, 15 | "ConnectionStrings": { 16 | "Mysql": "server=139.199.221.46;userid=djlnet;password=djlnet;database=test_productor;charset=utf8;", 17 | "LocalMysql": "server=localhost;userid=root;password=111111;database=test_productor;", 18 | "RabbitMq": "host=localhost;virtualHost=test;username=djlnet;password=djlnet;publisherConfirms=true;timeout=3;prefetchcount=50" 19 | }, 20 | "RedisConfig": { 21 | "Configuration": "139.199.221.46:6379", 22 | "InstanceName": "RedisTest" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Productor/Data/MqMessage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.EntityFrameworkCore.Metadata.Internal; 7 | 8 | namespace Productor.Data 9 | { 10 | public class MqMessage 11 | { 12 | public MqMessage() 13 | { 14 | Id = Guid.NewGuid(); 15 | CreateTime = DateTime.Now; 16 | } 17 | public Guid Id { get; set; } 18 | public bool IsPublished { get; set; } 19 | public string MessageAssemblyName { get; set; } 20 | public string MessageClassFullName { get; set; } 21 | public string Body { get; set; } 22 | public DateTime CreateTime { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Consumer/Mongo/MongoDbContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Consumer.MongoDbEntity; 6 | using Consumer.Option; 7 | using Microsoft.Extensions.Options; 8 | using MongoDB.Driver; 9 | 10 | namespace Consumer.Mongo 11 | { 12 | public class MongoDbContext 13 | { 14 | private readonly IMongoDatabase _database; 15 | 16 | public MongoDbContext(IOptions options) 17 | { 18 | var client = new MongoClient(options.Value.ConnectionString); 19 | _database = client.GetDatabase(options.Value.Database); 20 | } 21 | 22 | public IMongoCollection GuidEventLogs => _database.GetCollection("consumerlog"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Consumer/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "Debug": { 5 | "LogLevel": { 6 | "Default": "Warning" 7 | } 8 | }, 9 | "Console": { 10 | "LogLevel": { 11 | "Default": "Warning" 12 | } 13 | } 14 | }, 15 | "ConnectionStrings": { 16 | "Mysql": "server=139.199.221.46;userid=djlnet;password=djlnet;database=test_consumer;", 17 | "LocalMysql": "server=localhost;userid=root;password=111111;database=test_productor;", 18 | "RabbitMq": "host=localhost;virtualHost=test;username=djlnet;password=djlnet;publisherConfirms=true;timeout=3;prefetchcount=50" 19 | }, 20 | "MongoConnection": { 21 | "ConnectionString": "mongodb://djlnet:111111@139.199.221.46:27017", 22 | "Database": "test_consumerlog" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Productor/Quartz/TestHelloJob.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.Extensions.Logging; 7 | using Quartz; 8 | 9 | namespace Productor.Quartz 10 | { 11 | public class TestHelloJob : JobBase 12 | { 13 | private readonly ILogger _logger; 14 | 15 | public TestHelloJob(ILogger logger) 16 | { 17 | _logger = logger; 18 | } 19 | 20 | protected override ILogger Logger => _logger; 21 | protected override Task ExecuteJob(IJobExecutionContext context) 22 | { 23 | return Task.Run(() => 24 | { 25 | Debug.WriteLine("Hello djlnet"); 26 | }); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Consumer/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace Consumer 12 | { 13 | public class Program 14 | { 15 | public static void Main(string[] args) 16 | { 17 | BuildWebHost(args).Run(); 18 | } 19 | 20 | public static IWebHost BuildWebHost(string[] args) => 21 | WebHost.CreateDefaultBuilder(args) 22 | .UseContentRoot(Directory.GetCurrentDirectory()) 23 | .UseUrls("http://localhost:9999") 24 | .UseStartup() 25 | .Build(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Consumer/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:52737/", 7 | "sslPort": 0 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "launchUrl": "api/values", 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "Consumer": { 20 | "commandName": "Project", 21 | "launchBrowser": true, 22 | "launchUrl": "api/values", 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | }, 26 | "applicationUrl": "http://localhost:52738/" 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Productor/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace Productor 12 | { 13 | public class Program 14 | { 15 | public static void Main(string[] args) 16 | { 17 | BuildWebHost(args).Run(); 18 | } 19 | 20 | public static IWebHost BuildWebHost(string[] args) => 21 | WebHost.CreateDefaultBuilder(args) 22 | .UseContentRoot(Directory.GetCurrentDirectory()) 23 | .UseUrls("http://localhost:8888") 24 | .UseStartup() 25 | .Build(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Productor/Migrations/20180414032731_AddColumnToMqMessage.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Productor.Migrations 6 | { 7 | public partial class AddColumnToMqMessage : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.AddColumn( 12 | name: "IsPublished", 13 | table: "MqMessages", 14 | nullable: false, 15 | defaultValue: false); 16 | } 17 | 18 | protected override void Down(MigrationBuilder migrationBuilder) 19 | { 20 | migrationBuilder.DropColumn( 21 | name: "IsPublished", 22 | table: "MqMessages"); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Productor/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:52682/", 7 | "sslPort": 0 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "launchUrl": "api/values", 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "Productor": { 20 | "commandName": "Project", 21 | "launchBrowser": true, 22 | "launchUrl": "api/values", 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | }, 26 | "applicationUrl": "http://localhost:52683/" 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Productor/AutoMapper/OrderProfile.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AutoMapper; 6 | using Message; 7 | using Productor.Data; 8 | using Productor.Model; 9 | using OrderDetail = Productor.Data.OrderDetail; 10 | 11 | namespace Productor.AutoMapper 12 | { 13 | public class OrderProfile : Profile 14 | { 15 | public OrderProfile() 16 | { 17 | this.CreateMap(); 18 | this.CreateMap(); 19 | this.CreateMap(); 20 | this.CreateMap(); 21 | this.CreateMap(); 22 | this.CreateMap(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /XUnitTest/XUnitTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Productor/EventConsumer/EasyNetQConsumerBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using EasyNetQ.AutoSubscribe; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace Productor.EventConsumer 9 | { 10 | public abstract class EasyNetQConsumerBase : IConsume where T : class 11 | { 12 | public void Consume(T message) 13 | { 14 | try 15 | { 16 | ConsumeSync(message); 17 | } 18 | catch (Exception exception) 19 | { 20 | Logger.LogError(exception, $"{message.GetType().Name}消息消费者消费错误"); 21 | throw; 22 | } 23 | } 24 | 25 | protected abstract ILogger Logger { get; } 26 | protected abstract void ConsumeSync(T message); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Productor/Quartz/ClearHistoryMessageJob.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.Extensions.Logging; 6 | using Quartz; 7 | 8 | namespace Productor.Quartz 9 | { 10 | /// 11 | /// 清理历史消息记录保证消息表不会过载 12 | /// 13 | [IgnoreJob] 14 | public class ClearHistoryMessageJob : JobBase 15 | { 16 | private readonly ILogger _logger; 17 | 18 | public ClearHistoryMessageJob(ILogger logger) 19 | { 20 | _logger = logger; 21 | } 22 | 23 | protected override ILogger Logger => _logger; 24 | protected override async Task ExecuteJob(IJobExecutionContext context) 25 | { 26 | throw new NotImplementedException(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Consumer/EventConsumer/EasyNetQConsumerBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using EasyNetQ.AutoSubscribe; 6 | using Message; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace Consumer.EventConsumer 10 | { 11 | public abstract class EasyNetQConsumerBase : IConsume where T : AbstractEvent 12 | { 13 | public void Consume(T message) 14 | { 15 | try 16 | { 17 | ConsumeSync(message); 18 | } 19 | catch (Exception exception) 20 | { 21 | Logger.LogError(exception, $"{message.GetType().Name} 消息消费者消费错误"); 22 | throw; 23 | } 24 | } 25 | 26 | protected abstract ILogger Logger { get; } 27 | protected abstract void ConsumeSync(T message); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Productor/Data/EntityTypeMapConfig/OrderHeaderMapConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 7 | 8 | namespace Productor.Data.EntityTypeMapConfig 9 | { 10 | public class OrderHeaderMapConfig : IEntityTypeConfiguration 11 | { 12 | public void Configure(EntityTypeBuilder builder) 13 | { 14 | builder.HasKey(x => x.Id); 15 | builder.Property(x => x.Id).HasColumnType("char(36)"); 16 | builder.Property(x => x.AppUser).IsRequired().HasMaxLength(20); 17 | builder.Property(x => x.CreateTime).IsRequired().ValueGeneratedOnAdd(); 18 | builder.Property(x => x.Amount).IsRequired().HasColumnType("DECIMAL(18,2)").HasColumnName("Amount"); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Productor/Interceptor/LogExceptionAspectCoreInterceptorAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AspectCore.DynamicProxy; 6 | using AspectCore.Injector; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace Productor.Interceptor 10 | { 11 | public class LogExceptionAspectCoreInterceptorAttribute : AbstractInterceptor 12 | { 13 | [FromContainer] 14 | public ILogger Logger { get; set; } 15 | 16 | public override async Task Invoke(AspectContext context, AspectDelegate next) 17 | { 18 | try 19 | { 20 | await next(context); 21 | } 22 | catch (Exception e) 23 | { 24 | Logger.LogError(e, $"{context.ProxyMethod.Name}调用异常"); 25 | throw; 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Productor/Quartz/JobIntervalTriggerAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Productor.Quartz 7 | { 8 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] 9 | public class JobIntervalTriggerAttribute : Attribute 10 | { 11 | public JobIntervalTriggerAttribute(bool startNow = true, bool isRepeatForever = true, int intervalInSeconds = 60) 12 | { 13 | StartNow = startNow; 14 | IsRepeatForever = isRepeatForever; 15 | IntervalInSeconds = intervalInSeconds; 16 | } 17 | public string Key { get; set; } 18 | public string Group { get; set; } 19 | public bool StartNow { get; set; } 20 | public int IntervalInSeconds { get; set; } 21 | public bool IsRepeatForever { get; set; } 22 | public int RepeatCount { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Productor/Interceptor/LogExceptionCastleInterceptor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Castle.DynamicProxy; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace Productor.Interceptor 9 | { 10 | public class LogExceptionCastleInterceptor : Castle.DynamicProxy.IInterceptor 11 | { 12 | private readonly ILogger _logger; 13 | 14 | public LogExceptionCastleInterceptor(ILogger logger) 15 | { 16 | _logger = logger; 17 | } 18 | 19 | public void Intercept(IInvocation invocation) 20 | { 21 | try 22 | { 23 | invocation.Proceed(); 24 | } 25 | catch (Exception e) 26 | { 27 | _logger.LogError(e, $"{invocation.Method.Name}调用异常"); 28 | throw; 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Productor/Data/EntityTypeMapConfig/MqMessageTypeConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 7 | 8 | namespace Productor.Data.EntityTypeMapConfig 9 | { 10 | public class MqMessageTypeConfig : IEntityTypeConfiguration 11 | { 12 | public void Configure(EntityTypeBuilder builder) 13 | { 14 | builder.HasKey(x => x.Id); 15 | builder.Property(x => x.Id).HasColumnType("char(36)"); 16 | builder.Property(x => x.IsPublished).HasDefaultValue(false); 17 | builder.Property(x => x.MessageAssemblyName).IsRequired().HasMaxLength(200); 18 | builder.Property(x => x.MessageClassFullName).IsRequired().HasMaxLength(200); 19 | builder.Property(x => x.Body).IsRequired().HasMaxLength(4000); 20 | builder.Property(x => x.CreateTime).IsRequired().ValueGeneratedOnAdd(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Productor/Data/ProductDbContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.EntityFrameworkCore; 6 | using Productor.Data.EntityTypeMapConfig; 7 | 8 | namespace Productor.Data 9 | { 10 | public class ProductDbContext : DbContext 11 | { 12 | public ProductDbContext(DbContextOptions options) : base(options) 13 | { 14 | 15 | } 16 | 17 | protected override void OnModelCreating(ModelBuilder modelBuilder) 18 | { 19 | modelBuilder.ApplyConfiguration(new MqMessageTypeConfig()); 20 | modelBuilder.ApplyConfiguration(new OrderDetailMapConfig()); 21 | modelBuilder.ApplyConfiguration(new OrderHeaderMapConfig()); 22 | 23 | base.OnModelCreating(modelBuilder); 24 | } 25 | 26 | public DbSet MqMessages { get; set; } 27 | public DbSet OrderHeaders { get; set; } 28 | public DbSet OrderDetails { get; set; } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Message/OrderCreatedEvent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Message 5 | { 6 | [Serializable] 7 | public class OrderCreatedEvent : AbstractEvent 8 | { 9 | public OrderCreatedEvent() : base() 10 | { 11 | CreateTime = DateTime.Now; 12 | } 13 | public Guid Id { get; set; } 14 | public decimal Amount { get; set; } 15 | public DateTime CreateTime { get; set; } 16 | public string AppUser { get; set; } 17 | 18 | public IList Details { get; set; } 19 | } 20 | 21 | public class OrderDetail 22 | { 23 | public OrderDetail() 24 | { 25 | CreateTime = DateTime.Now; 26 | } 27 | public Guid Id { get; set; } 28 | public Guid ParentId { get; set; } 29 | public string Sku { get; set; } 30 | public string SkuName { get; set; } 31 | public int Quantity { get; set; } 32 | public decimal Price { get; set; } 33 | public DateTime CreateTime { get; set; } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Productor/Quartz/JobBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.Extensions.Logging; 6 | using Quartz; 7 | 8 | namespace Productor.Quartz 9 | { 10 | [DisallowConcurrentExecution] 11 | [PersistJobDataAfterExecution] 12 | public abstract class JobBase : IJob 13 | { 14 | protected abstract ILogger Logger { get; } 15 | 16 | public Task Execute(IJobExecutionContext context) 17 | { 18 | try 19 | { 20 | return ExecuteJob(context); 21 | } 22 | catch (Exception exception) 23 | { 24 | Logger.LogError(exception, $"当前任务key:{context.JobDetail.Key};当前任务描述desc:{context.JobDetail.Description}执行出现未知异常"); 25 | JobExecutionException jobExecutionException = new JobExecutionException(exception, refireImmediately: true); 26 | throw jobExecutionException; 27 | } 28 | } 29 | 30 | protected abstract Task ExecuteJob(IJobExecutionContext context); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Consumer/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace Consumer.Controllers 8 | { 9 | [Route("api/[controller]")] 10 | public class ValuesController : Controller 11 | { 12 | // GET api/values 13 | [HttpGet] 14 | public IEnumerable Get() 15 | { 16 | return new string[] { "value1", "value2" }; 17 | } 18 | 19 | // GET api/values/5 20 | [HttpGet("{id}")] 21 | public string Get(int id) 22 | { 23 | return "value"; 24 | } 25 | 26 | // POST api/values 27 | [HttpPost] 28 | public void Post([FromBody]string value) 29 | { 30 | } 31 | 32 | // PUT api/values/5 33 | [HttpPut("{id}")] 34 | public void Put(int id, [FromBody]string value) 35 | { 36 | } 37 | 38 | // DELETE api/values/5 39 | [HttpDelete("{id}")] 40 | public void Delete(int id) 41 | { 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Productor/Data/EntityTypeMapConfig/OrderDetailMapConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 7 | 8 | namespace Productor.Data.EntityTypeMapConfig 9 | { 10 | public class OrderDetailMapConfig : IEntityTypeConfiguration 11 | { 12 | public void Configure(EntityTypeBuilder builder) 13 | { 14 | builder.HasKey(x => x.Id); 15 | builder.Property(x => x.Id).HasColumnType("char(36)"); 16 | builder.Property(x => x.ParentId).IsRequired().HasColumnType("char(36)"); 17 | builder.Property(x => x.Sku).IsRequired().HasMaxLength(50); 18 | builder.Property(x => x.SkuName).IsRequired().HasMaxLength(50); 19 | builder.Property(x => x.Quantity).IsRequired().HasColumnName("Quantity"); 20 | builder.Property(x => x.Price).IsRequired().HasColumnType("DECIMAL(18,2)").HasColumnName("Price"); 21 | builder.Property(x => x.CreateTime).IsRequired().ValueGeneratedOnAdd(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Productor/Common/ApiResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Productor.Common 7 | { 8 | [Serializable] 9 | public class ApiResult where T : class, new() 10 | { 11 | public ApiResult() 12 | { 13 | this.Message = string.Empty; 14 | this.Successed = true; 15 | this.DevelopMessage = string.Empty; 16 | } 17 | 18 | public ApiResult(bool successed = true) 19 | { 20 | this.Successed = successed; 21 | } 22 | 23 | public bool Successed { get; set; } 24 | public T Data { get; set; } 25 | public object DevelopMessage { get; set; } 26 | public string Message { get; set; } 27 | } 28 | 29 | public class ApiResult : ApiResult 30 | { 31 | public ApiResult() 32 | { 33 | this.Message = string.Empty; 34 | this.Successed = true; 35 | this.DevelopMessage = string.Empty; 36 | } 37 | 38 | public ApiResult(bool successed = true) : base(successed) 39 | { 40 | 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Productor/Controllers/ControllerBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Newtonsoft.Json; 7 | using Productor.Common; 8 | 9 | namespace Productor.Controllers 10 | { 11 | [Produces("application/json")] 12 | public abstract class ControllerBase : Controller 13 | { 14 | public override JsonResult Json(object data) 15 | { 16 | var apiResult = new ApiResult(true) 17 | { 18 | Data = data 19 | }; 20 | return base.Json(apiResult); 21 | } 22 | 23 | public override JsonResult Json(object data, JsonSerializerSettings serializerSettings) 24 | { 25 | var apiResult = new ApiResult(true) 26 | { 27 | Data = data 28 | }; 29 | return base.Json(apiResult, serializerSettings); 30 | } 31 | 32 | /// 33 | /// 表示返回正确的操作成功状态 34 | /// 35 | /// 36 | [NonAction] 37 | protected JsonResult Json() 38 | { 39 | return base.Json(new ApiResult(true)); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Consumer/Consumer.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Productor/Model/OrderInput.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Productor.Model 8 | { 9 | /// 10 | /// 订单 11 | /// 12 | public class OrderInput 13 | { 14 | public OrderInput() 15 | { 16 | Details = new List(); 17 | } 18 | /// 19 | /// 用户 20 | /// 21 | [Required] 22 | [StringLength(20)] 23 | public string AppUser { get; set; } 24 | /// 25 | /// 订单明细 26 | /// 27 | public IList Details { get; set; } 28 | 29 | } 30 | 31 | /// 32 | /// 订单明细 33 | /// 34 | public class OrderDetailInput 35 | { 36 | /// 37 | /// 商品SKU 38 | /// 39 | [Required] 40 | [StringLength(50)] 41 | public string Sku { get; set; } 42 | /// 43 | /// 商品名称 44 | /// 45 | [Required] 46 | [StringLength(50)] 47 | public string SkuName { get; set; } 48 | /// 49 | /// 数量 50 | /// 51 | public int Quantity { get; set; } 52 | /// 53 | /// 单价 54 | /// 55 | public decimal Price { get; set; } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Productor/Migrations/20180414013731_SettingDeciaml.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Productor.Migrations 6 | { 7 | public partial class SettingDeciaml : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.AlterColumn( 12 | name: "Amount", 13 | table: "OrderHeaders", 14 | type: "DECIMAL(18,2)", 15 | nullable: false, 16 | oldClrType: typeof(decimal)); 17 | 18 | migrationBuilder.AlterColumn( 19 | name: "Price", 20 | table: "OrderDetails", 21 | type: "DECIMAL(18,2)", 22 | nullable: false, 23 | oldClrType: typeof(decimal)); 24 | } 25 | 26 | protected override void Down(MigrationBuilder migrationBuilder) 27 | { 28 | migrationBuilder.AlterColumn( 29 | name: "Amount", 30 | table: "OrderHeaders", 31 | nullable: false, 32 | oldClrType: typeof(decimal), 33 | oldType: "DECIMAL(18,2)"); 34 | 35 | migrationBuilder.AlterColumn( 36 | name: "Price", 37 | table: "OrderDetails", 38 | nullable: false, 39 | oldClrType: typeof(decimal), 40 | oldType: "DECIMAL(18,2)"); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Productor/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace Productor.Controllers 9 | { 10 | [Route("api/[controller]")] 11 | public class ValuesController : Controller 12 | { 13 | private readonly ILogger _logger; 14 | 15 | public ValuesController(ILogger logger) 16 | { 17 | _logger = logger; 18 | } 19 | 20 | // GET api/values 21 | [HttpGet] 22 | public IEnumerable Get() 23 | { 24 | return new string[] { "value1", "value2" }; 25 | } 26 | 27 | [HttpGet] 28 | [Route("testerror")] 29 | public string TestErrorLog(int id) 30 | { 31 | _logger.LogError(new Exception("test"),"我是来测试error的"); 32 | return "testerror"; 33 | } 34 | 35 | // GET api/values/5 36 | [HttpGet("{id}")] 37 | public string Get(int id) 38 | { 39 | return "value"; 40 | } 41 | 42 | // POST api/values 43 | [HttpPost] 44 | public void Post([FromBody]string value) 45 | { 46 | } 47 | 48 | // PUT api/values/5 49 | [HttpPut("{id}")] 50 | public void Put(int id, [FromBody]string value) 51 | { 52 | } 53 | 54 | // DELETE api/values/5 55 | [HttpDelete("{id}")] 56 | public void Delete(int id) 57 | { 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Productor/Migrations/20180413034406_UpdateOrderConfig.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Productor.Migrations 6 | { 7 | public partial class UpdateOrderConfig : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.DropColumn( 12 | name: "No", 13 | table: "OrderHeaders"); 14 | 15 | migrationBuilder.DropColumn( 16 | name: "OrderNo", 17 | table: "OrderDetails"); 18 | 19 | migrationBuilder.AddColumn( 20 | name: "ParentId", 21 | table: "OrderDetails", 22 | type: "char(36)", 23 | nullable: false, 24 | defaultValue: new Guid("00000000-0000-0000-0000-000000000000")); 25 | } 26 | 27 | protected override void Down(MigrationBuilder migrationBuilder) 28 | { 29 | migrationBuilder.DropColumn( 30 | name: "ParentId", 31 | table: "OrderDetails"); 32 | 33 | migrationBuilder.AddColumn( 34 | name: "No", 35 | table: "OrderHeaders", 36 | maxLength: 50, 37 | nullable: false, 38 | defaultValue: ""); 39 | 40 | migrationBuilder.AddColumn( 41 | name: "OrderNo", 42 | table: "OrderDetails", 43 | maxLength: 50, 44 | nullable: false, 45 | defaultValue: ""); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Productor/Interceptor/CacheAspectCoreInterceptorAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AspectCore.DynamicProxy; 6 | using AspectCore.Injector; 7 | using Microsoft.Extensions.Caching.Memory; 8 | 9 | namespace Productor.Interceptor 10 | { 11 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] 12 | public class CacheAspectCoreInterceptorAttribute : AbstractInterceptorAttribute 13 | { 14 | [FromContainer] 15 | public IMemoryCache MemoryCache { get; set; } 16 | 17 | public override async Task Invoke(AspectContext context, AspectDelegate next) 18 | { 19 | var cacheKey = GenerateCacheKey(context.ProxyMethod.Name, context.Parameters); 20 | if (MemoryCache.TryGetValue(cacheKey, out object value)) 21 | { 22 | context.ReturnValue = MemoryCache.Get(cacheKey); 23 | } 24 | else 25 | { 26 | await next(context); 27 | var item = context.ReturnValue; 28 | MemoryCache.Set(cacheKey, item, new MemoryCacheEntryOptions() 29 | { 30 | SlidingExpiration = TimeSpan.FromSeconds(10) 31 | }); 32 | } 33 | } 34 | 35 | private static string GenerateCacheKey(string name, object[] arguments) 36 | { 37 | if (arguments == null || arguments.Length == 0) 38 | return name; 39 | return name + "_" + string.Join("_", arguments.Select(a => a.ToString()).ToArray()); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Productor/Controllers/OrderController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AutoMapper; 6 | using JetBrains.Annotations; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Newtonsoft.Json; 9 | using Newtonsoft.Json.Serialization; 10 | using Productor.Model; 11 | using Productor.Service; 12 | 13 | // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 14 | 15 | namespace Productor.Controllers 16 | { 17 | /// 18 | /// 订单服务 19 | /// 20 | [Route("api/[controller]")] 21 | public class OrderController : ControllerBase 22 | { 23 | //private readonly IMapper _mapper; 24 | private readonly IOrderService _orderService; 25 | 26 | public OrderController(IOrderService orderService) 27 | { 28 | //_mapper = mapper; 29 | _orderService = orderService; 30 | } 31 | 32 | /// 33 | /// 获取订单头和明细 34 | /// 35 | /// 36 | /// 37 | [HttpGet] 38 | [AcceptVerbs("GET")] 39 | public IActionResult Get([FromQuery]Guid id) 40 | { 41 | return Json(_orderService.GetOrderInfo(id)); 42 | } 43 | 44 | /// 45 | /// 创建订单 46 | /// 47 | /// 48 | /// 49 | [HttpPost] 50 | [AcceptVerbs("POST")] 51 | public IActionResult Create([FromBody]OrderInput input) 52 | { 53 | _orderService.CreateOrder(input); 54 | return Json(); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Productor/Quartz/ProductorJobFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Logging; 8 | using Quartz; 9 | using Quartz.Simpl; 10 | using Quartz.Spi; 11 | 12 | namespace Productor.Quartz 13 | { 14 | public class ProductorJobFactory : IJobFactory 15 | { 16 | private readonly ILogger _logger; 17 | private readonly IServiceProvider _serviceProvider; 18 | 19 | public ProductorJobFactory(ILogger logger, IServiceProvider serviceProvider) 20 | { 21 | _logger = logger; 22 | _serviceProvider = serviceProvider; 23 | } 24 | 25 | public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) 26 | { 27 | try 28 | { 29 | var job = this._serviceProvider.GetRequiredService(bundle.JobDetail.JobType) as IJob; 30 | if (job == null) 31 | throw new ArgumentNullException($"{nameof(job)}"); 32 | return job; 33 | } 34 | catch (Exception exception) 35 | { 36 | _logger.LogError(exception, $"Problem while instantiating job '{bundle.JobDetail.Key}' from the ProductorJobFactory."); 37 | throw new SchedulerException($"Problem while instantiating job '{bundle.JobDetail.Key}' from the ProductorJobFactory.", exception); 38 | } 39 | } 40 | 41 | public void ReturnJob(IJob job) 42 | { 43 | var disposable = job as IDisposable; 44 | disposable?.Dispose(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Productor/Filter/ValidateModelStateAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.AspNetCore.Mvc.Filters; 7 | using Microsoft.EntityFrameworkCore.Internal; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Logging; 10 | using Productor.Common; 11 | 12 | namespace Productor.Filter 13 | { 14 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] 15 | public class ValidateModelStateAttribute : ActionFilterAttribute 16 | { 17 | public override void OnActionExecuting(ActionExecutingContext context) 18 | { 19 | if (!context.ModelState.IsValid) 20 | { 21 | var list = (from modelState in context.ModelState.Values 22 | from error in modelState.Errors 23 | select new { error.ErrorMessage, error.Exception }).ToList(); 24 | 25 | //Also add exceptions. 26 | //list.AddRange(from modelState in context.ModelState.Values from error in modelState.Errors select error.Exception.ToString()); 27 | 28 | // 记录客户端错误消息 29 | var logger = context.HttpContext.RequestServices 30 | .GetRequiredService>(); 31 | logger.LogDebug(list.First().Exception, list.First().ErrorMessage); 32 | 33 | context.Result = new JsonResult(new ApiResult(false) 34 | { 35 | Message = list.First().ErrorMessage 36 | }); 37 | } 38 | 39 | base.OnActionExecuting(context); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Consumer/EventConsumer/OrderCreatedEventConsumer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AutoMapper; 6 | using Consumer.Mongo; 7 | using Consumer.MongoDbEntity; 8 | using EasyNetQ.AutoSubscribe; 9 | using EasyNetQ.Consumer; 10 | using Message; 11 | using Microsoft.Extensions.Logging; 12 | using Newtonsoft.Json; 13 | using Polly; 14 | 15 | namespace Consumer.EventConsumer 16 | { 17 | public class OrderCreatedEventConsumer : EasyNetQConsumerBase 18 | { 19 | private readonly ILogger _logger; 20 | private readonly MongoDbContext _mongoDbContext; 21 | private readonly IMapper _mapper; 22 | 23 | public OrderCreatedEventConsumer(ILogger logger, MongoDbContext mongoDbContext, IMapper mapper) 24 | { 25 | _logger = logger; 26 | _mongoDbContext = mongoDbContext; 27 | _mapper = mapper; 28 | } 29 | 30 | protected override ILogger Logger => _logger; 31 | 32 | protected override void ConsumeSync(OrderCreatedEvent message) 33 | { 34 | // 拿到rabbitmq消息消费需要持久化,消费失败需要自动重试消费 35 | _logger.LogDebug(JsonConvert.SerializeObject(message)); 36 | // 尝试写入Mongo持久化消息存储,方便手动重试下消费或者自动消费逻辑 37 | var mongoItem = _mapper.Map(message); 38 | mongoItem.Body = JsonConvert.SerializeObject(message); 39 | mongoItem.MessageClassFullName = message.GetType().FullName; 40 | mongoItem.MessageAssemblyName = typeof(OrderCreatedEvent).Assembly.GetName().Name; 41 | Policy.Handle().Retry(3).Execute(() => _mongoDbContext.GuidEventLogs.InsertOne(mongoItem)); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Productor/Filter/GlobalExceptionFilter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Microsoft.AspNetCore.Mvc.Filters; 8 | using Microsoft.Extensions.Logging; 9 | using Productor.Common; 10 | 11 | namespace Productor.Filter 12 | { 13 | public class GlobalExceptionFilter : IExceptionFilter 14 | { 15 | private readonly IHostingEnvironment _hostingEnvironment; 16 | private readonly ILogger _logger; 17 | 18 | public GlobalExceptionFilter(IHostingEnvironment hostingEnvironment, ILogger logger) 19 | { 20 | _hostingEnvironment = hostingEnvironment; 21 | _logger = logger; 22 | } 23 | 24 | public void OnException(ExceptionContext context) 25 | { 26 | 27 | var errorJsonResult = new ApiResult(false); 28 | if (_hostingEnvironment.IsDevelopment()) 29 | { 30 | errorJsonResult.Message = context.Exception.Message; 31 | errorJsonResult.DevelopMessage = context.Exception.StackTrace; 32 | _logger.LogError(context.Exception, context.Exception.Message); 33 | } 34 | else 35 | { 36 | if (context.Exception is KnownException) 37 | { 38 | errorJsonResult.Message = context.Exception.Message; 39 | } 40 | else 41 | { 42 | errorJsonResult.Message = "内部出现未知异常"; 43 | _logger.LogError(context.Exception, context.Exception.Message); 44 | } 45 | } 46 | context.Result = new JsonResult(errorJsonResult); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Productor/Interceptor/RedisCacheAspectCoreInterceptorAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AspectCore.DynamicProxy; 6 | using AspectCore.Injector; 7 | using Microsoft.Extensions.Caching.Distributed; 8 | using Newtonsoft.Json; 9 | 10 | namespace Productor.Interceptor 11 | { 12 | public class RedisCacheAspectCoreInterceptorAttribute : AbstractInterceptorAttribute 13 | { 14 | [FromContainer] 15 | public IDistributedCache DistributedCache { get; set; } 16 | 17 | public override async Task Invoke(AspectContext context, AspectDelegate next) 18 | { 19 | var cacheKey = GenerateCacheKey(context.ProxyMethod.Name, context.Parameters); 20 | var str = await DistributedCache.GetStringAsync(cacheKey); 21 | if (!string.IsNullOrWhiteSpace(str)) 22 | { 23 | var value = JsonConvert.DeserializeObject(str, context.ProxyMethod.ReturnType); 24 | context.ReturnValue = value; 25 | } 26 | else 27 | { 28 | await next(context); 29 | var item = context.ReturnValue; 30 | await DistributedCache.SetStringAsync(cacheKey, JsonConvert.SerializeObject(item), 31 | new DistributedCacheEntryOptions() 32 | { 33 | SlidingExpiration = TimeSpan.FromSeconds(10) 34 | }); 35 | } 36 | } 37 | 38 | private static string GenerateCacheKey(string name, object[] arguments) 39 | { 40 | if (arguments == null || arguments.Length == 0) 41 | return name; 42 | return name + "_" + string.Join("_", arguments.Select(a => a.ToString()).ToArray()); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Productor/Common/RabbitMqEventBus.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using EasyNetQ; 6 | using EasyNetQ.NonGeneric; 7 | using Polly; 8 | using Polly.Retry; 9 | 10 | namespace Productor.Common 11 | { 12 | public class RabbitMqEventBus : IEventBus 13 | { 14 | private readonly IBus _bus; 15 | 16 | private readonly RetryPolicy _retryPolicy; 17 | 18 | private readonly RetryPolicy _retryPolicyAsync; 19 | 20 | public RabbitMqEventBus(IBus bus) 21 | { 22 | _bus = bus; 23 | _retryPolicy = Policy.Handle().WaitAndRetry(new[] 24 | { 25 | TimeSpan.FromSeconds(0.5), 26 | TimeSpan.FromSeconds(1), 27 | TimeSpan.FromSeconds(2) 28 | }); 29 | _retryPolicyAsync = Policy.Handle().WaitAndRetryAsync(new[] 30 | { 31 | TimeSpan.FromSeconds(0.5), 32 | TimeSpan.FromSeconds(1), 33 | TimeSpan.FromSeconds(2) 34 | }); 35 | } 36 | public void Publish(T message) where T : class, new() 37 | { 38 | _retryPolicy.Execute(() => _bus.Publish(message)); 39 | } 40 | 41 | public async Task PublishAsync(T message) where T : class, new() 42 | { 43 | await _retryPolicyAsync.ExecuteAsync(() => _bus.PublishAsync(message)); 44 | } 45 | 46 | public void Publish(Type messageType, object message) 47 | { 48 | _retryPolicy.Execute(() => _bus.Publish(messageType, message)); 49 | } 50 | 51 | public void PublishAsync(Type messageType, object message) 52 | { 53 | _retryPolicy.ExecuteAsync(() => _bus.PublishAsync(messageType, message)); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Consumer/EasyNetQ/ConsumerMessageDispatcher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using EasyNetQ.AutoSubscribe; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace Consumer.EasyNetQ 10 | { 11 | public class ConsumerMessageDispatcher : IAutoSubscriberMessageDispatcher 12 | { 13 | private readonly IServiceProvider _serviceProvider; 14 | private readonly ILogger _logger; 15 | 16 | public ConsumerMessageDispatcher(IServiceProvider serviceProvider, ILogger logger) 17 | { 18 | _serviceProvider = serviceProvider; 19 | _logger = logger; 20 | } 21 | 22 | public void Dispatch(TMessage message) where TMessage : class where TConsumer : IConsume 23 | { 24 | try 25 | { 26 | TConsumer consumer = _serviceProvider.GetRequiredService(); 27 | consumer.Consume(message); 28 | } 29 | catch (Exception exception) 30 | { 31 | _logger.LogError(exception, $"创建消费者或者消费异常"); 32 | throw; 33 | } 34 | } 35 | 36 | public async Task DispatchAsync(TMessage message) where TMessage : class where TConsumer : IConsumeAsync 37 | { 38 | try 39 | { 40 | TConsumer consumer = _serviceProvider.GetRequiredService(); 41 | await consumer.Consume(message); 42 | } 43 | catch (Exception exception) 44 | { 45 | _logger.LogError(exception, $"创建消费者或者消费异常"); 46 | throw; 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Productor/EasyNetQ/ProductorMessageDispatcher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using EasyNetQ.AutoSubscribe; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace Productor.EasyNetQ 10 | { 11 | public class ProductorMessageDispatcher : IAutoSubscriberMessageDispatcher 12 | { 13 | private readonly IServiceProvider _serviceProvider; 14 | private readonly ILogger _logger; 15 | 16 | public ProductorMessageDispatcher(IServiceProvider serviceProvider, ILogger logger) 17 | { 18 | _serviceProvider = serviceProvider; 19 | _logger = logger; 20 | } 21 | 22 | public void Dispatch(TMessage message) where TMessage : class where TConsumer : IConsume 23 | { 24 | try 25 | { 26 | TConsumer consumer = _serviceProvider.GetRequiredService(); 27 | consumer.Consume(message); 28 | } 29 | catch (Exception exception) 30 | { 31 | _logger.LogError(exception, $"创建消费者或者消费异常"); 32 | throw; 33 | } 34 | } 35 | 36 | public async Task DispatchAsync(TMessage message) where TMessage : class where TConsumer : IConsumeAsync 37 | { 38 | try 39 | { 40 | TConsumer consumer = _serviceProvider.GetRequiredService(); 41 | await consumer.Consume(message); 42 | } 43 | catch (Exception exception) 44 | { 45 | _logger.LogError(exception, $"创建消费者或者消费异常"); 46 | throw; 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Productor/Model/OrderOutput.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Productor.Model 7 | { 8 | /// 9 | /// 订单 10 | /// 11 | public class OrderOutput 12 | { 13 | public OrderOutput() 14 | { 15 | Details = new List(); 16 | } 17 | 18 | /// 19 | /// 订单主键 20 | /// 21 | public Guid Id { get; set; } 22 | /// 23 | /// 总价值 24 | /// 25 | public decimal Amount { get; set; } 26 | /// 27 | /// 下单时间 28 | /// 29 | public DateTime CreateTime { get; set; } 30 | /// 31 | /// 下单用户 32 | /// 33 | public string AppUser { get; set; } 34 | /// 35 | /// 订单详情 36 | /// 37 | public IList Details { get; set; } 38 | } 39 | 40 | /// 41 | /// 订单详情 42 | /// 43 | public class OrderDetailOutput 44 | { 45 | /// 46 | /// 详情主键 47 | /// 48 | public Guid Id { get; set; } 49 | /// 50 | /// 订单主键 51 | /// 52 | public Guid ParentId { get; set; } 53 | /// 54 | /// 商品SKU 55 | /// 56 | public string Sku { get; set; } 57 | /// 58 | /// 商品名称 59 | /// 60 | public string SkuName { get; set; } 61 | /// 62 | /// 数量 63 | /// 64 | public int Quantity { get; set; } 65 | /// 66 | /// 单价 67 | /// 68 | public decimal Price { get; set; } 69 | /// 70 | /// 创建时间 71 | /// 72 | public DateTime CreateTime { get; set; } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /Productor/Swagger/SwaggerExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Threading.Tasks; 7 | using Microsoft.AspNetCore.Builder; 8 | using Microsoft.AspNetCore.Builder.Internal; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Swashbuckle.AspNetCore.Swagger; 11 | 12 | namespace Productor.Swagger 13 | { 14 | public static class SwaggerExtension 15 | { 16 | public static void AddSwagger(this IServiceCollection services) 17 | { 18 | // Register the Swagger generator, defining one or more Swagger documents 19 | services.AddSwaggerGen(c => 20 | { 21 | c.SwaggerDoc("v1", new Info 22 | { 23 | Title = "Order Open Api", 24 | Version = "v1", 25 | Description = "Order Open Api", 26 | TermsOfService = "None", 27 | Contact = new Contact() 28 | { 29 | Name = "djlnet", 30 | Email = "972417907@qq.com", 31 | Url = "http://www.djlnet.com" 32 | }, 33 | License = new License 34 | { 35 | Name = "Djlnet License", 36 | Url = "http://djlnet.com/license" 37 | } 38 | }); 39 | 40 | // Set the comments path for the Swagger JSON and UI. 41 | var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml"; 42 | var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); 43 | c.IncludeXmlComments(xmlPath); 44 | }); 45 | } 46 | 47 | public static void UseSwaggerAll(this IApplicationBuilder app) 48 | { 49 | // Enable middleware to serve generated Swagger as a JSON endpoint. 50 | app.UseSwagger(); 51 | 52 | // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint. 53 | app.UseSwaggerUI(c => 54 | { 55 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "Order Open Api V1"); 56 | }); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Consumer/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AutoMapper; 6 | using Consumer.AutoMapper; 7 | using Consumer.EasyNetQ; 8 | using Consumer.Mongo; 9 | using Consumer.Option; 10 | using Microsoft.AspNetCore.Builder; 11 | using Microsoft.AspNetCore.Hosting; 12 | using Microsoft.Extensions.Configuration; 13 | using Microsoft.Extensions.DependencyInjection; 14 | using Microsoft.Extensions.Logging; 15 | using Microsoft.Extensions.Options; 16 | 17 | namespace Consumer 18 | { 19 | public class Startup 20 | { 21 | public Startup(IConfiguration configuration) 22 | { 23 | Configuration = configuration; 24 | } 25 | 26 | public IConfiguration Configuration { get; } 27 | 28 | // This method gets called by the runtime. Use this method to add services to the container. 29 | public void ConfigureServices(IServiceCollection services) 30 | { 31 | // 官方package默认scope 32 | //services.AddAutoMapper(x => 33 | //{ 34 | // x.AllowNullCollections = true; 35 | //}); 36 | 37 | // 利用第三方的包实现Singleton模式 38 | services.AddAutoMapper(mapperLifetime: ServiceLifetime.Singleton); 39 | 40 | services.AddMvc(); 41 | 42 | services.Configure(x => 43 | { 44 | x.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value; 45 | x.Database = Configuration.GetSection("MongoConnection:Database").Value; 46 | }); 47 | 48 | services.AddSingleton(); 49 | 50 | services.AddEasyNetQ(Configuration.GetConnectionString("RabbitMq")); 51 | } 52 | 53 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 54 | public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime) 55 | { 56 | if (env.IsDevelopment()) 57 | { 58 | app.UseDeveloperExceptionPage(); 59 | } 60 | 61 | loggerFactory.AddConsole(LogLevel.Trace); 62 | loggerFactory.AddLog4Net("log4net.config"); 63 | 64 | app.UseStaticFiles(); 65 | app.UseMvc(); 66 | app.UseEasyNetQ(); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Productor/Filter/ExceptionActionFilter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.AspNetCore.Http; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Microsoft.AspNetCore.Mvc.Filters; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace Productor.Filter 12 | { 13 | public class ExceptionActionFilter : IExceptionFilter 14 | { 15 | private readonly IHostingEnvironment _hostingEnvironment; 16 | private readonly ILogger _logger; 17 | 18 | public ExceptionActionFilter(IHostingEnvironment hostingEnvironment, ILogger logger) 19 | { 20 | _hostingEnvironment = hostingEnvironment; 21 | _logger = logger; 22 | } 23 | 24 | public void OnException(ExceptionContext context) 25 | { 26 | var json = new JsonErrorReponse(); 27 | if (context.Exception is UserOperationException) 28 | { 29 | json.Message = context.Exception.Message; 30 | json.DevelopMessage = context.Exception.StackTrace; 31 | context.Result = new BadRequestObjectResult(json); 32 | } 33 | else 34 | { 35 | json.Message = "未知内部异常"; 36 | if (_hostingEnvironment.IsDevelopment()) 37 | { 38 | json.DevelopMessage = context.Exception.StackTrace; 39 | } 40 | context.Result = new InternalServerErrorObjectResult(json); 41 | } 42 | _logger.LogError(context.Exception, context.Exception.Message); 43 | } 44 | } 45 | 46 | public class InternalServerErrorObjectResult : ObjectResult 47 | { 48 | public InternalServerErrorObjectResult(object value) : base(value) 49 | { 50 | StatusCode = StatusCodes.Status500InternalServerError; 51 | } 52 | } 53 | 54 | public class JsonErrorReponse 55 | { 56 | public string Message { get; set; } 57 | public object DevelopMessage { get; set; } 58 | } 59 | 60 | public class UserOperationException : Exception 61 | { 62 | public UserOperationException() 63 | { 64 | 65 | } 66 | 67 | public UserOperationException(string message) : base(message) 68 | { 69 | 70 | } 71 | 72 | public UserOperationException(string message, Exception innerException) : base(message, innerException) 73 | { 74 | 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Productor/Productor.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.0 5 | 6 | 7 | 8 | bin\Debug\netcoreapp2.0\Productor.xml 9 | 1701;1702;1705;1591 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /Productor/Service/OrderService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AspectCore.DynamicProxy.Parameters; 6 | using AutoMapper; 7 | using Message; 8 | using Newtonsoft.Json; 9 | using Newtonsoft.Json.Serialization; 10 | using Productor.Common; 11 | using Productor.Data; 12 | using Productor.Model; 13 | 14 | namespace Productor.Service 15 | { 16 | public class OrderService : IOrderService 17 | { 18 | private readonly ProductDbContext _dbContext; 19 | private readonly IMapper _mapper; 20 | 21 | public OrderService(ProductDbContext dbContext, IMapper mapper) 22 | { 23 | _dbContext = dbContext; 24 | _mapper = mapper; 25 | } 26 | 27 | public OrderOutput GetOrderInfo(Guid id) 28 | { 29 | var header = _dbContext.OrderHeaders.SingleOrDefault(x => x.Id == id); 30 | if (header == null) throw new KnownException($"{id}参数错误找不到订单"); 31 | var details = _dbContext.OrderDetails.Where(x => x.ParentId == header.Id).ToList(); 32 | if (details == null || !details.Any()) throw new KnownException($"{id}参数错误找不到订单详情"); 33 | var ouput = _mapper.Map(header); 34 | ouput.Details = _mapper.Map>(details); 35 | return ouput; 36 | } 37 | 38 | public void CreateOrder(OrderInput input) 39 | { 40 | if (input.Details == null || !input.Details.Any()) throw new KnownException("订单错误找不到详情"); 41 | var header = _mapper.Map(input); 42 | var details = _mapper.Map>(input.Details); 43 | details.ForEach(x => x.ParentId = header.Id); 44 | header.Amount = details.Sum(x => x.Price * x.Quantity); 45 | var msg = _mapper.Map(header); 46 | msg.Details = _mapper.Map>(details); 47 | var dbMessage = new MqMessage() 48 | { 49 | Body = JsonConvert.SerializeObject(msg, new JsonSerializerSettings() 50 | { 51 | ContractResolver = new CamelCasePropertyNamesContractResolver(), 52 | DateFormatString = "yyyy-MM-dd hh:mm:ss" 53 | }), 54 | MessageAssemblyName = typeof(OrderCreatedEvent).Assembly.GetName().Name, 55 | MessageClassFullName = msg.GetType().FullName 56 | }; 57 | _dbContext.Add(dbMessage); 58 | _dbContext.Add(header); 59 | _dbContext.AddRange(details); 60 | _dbContext.SaveChanges(); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /Productor/EasyNetQ/EasyNetQExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Threading.Tasks; 6 | using EasyNetQ; 7 | using EasyNetQ.AutoSubscribe; 8 | using EasyNetQ.Consumer; 9 | using Microsoft.AspNetCore.Builder; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Microsoft.Extensions.Logging; 12 | using Productor.EventConsumer; 13 | 14 | namespace Productor.EasyNetQ 15 | { 16 | public static class EasyNetQExtension 17 | { 18 | private static void InternalInitEasyNetQ(IServiceCollection service, string rabbitMqConnection) 19 | { 20 | var bus = RabbitHutch.CreateBus(rabbitMqConnection); 21 | service.AddSingleton(bus); 22 | service.AddSingleton(serviceProvider => new ProductorMessageDispatcher(serviceProvider, serviceProvider.GetRequiredService>())); 23 | 24 | var consumerTypes = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface).Where(x => x.BaseType.Name == typeof(EasyNetQConsumerBase<>).Name || x.GetInterfaces().Any(t => t.Name == typeof(IConsume<>).Name)); 25 | 26 | foreach (var consumerType in consumerTypes) 27 | { 28 | service.AddTransient(consumerType); 29 | //service.AddTransient(typeof(IConsume<>), consumerType); 30 | } 31 | 32 | var consumerAsyncTypes = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface) 33 | .Where(x => x.GetInterfaces().Any(t => t.Name == typeof(IConsumeAsync<>).Name)); 34 | 35 | foreach (var consumerAsyncType in consumerAsyncTypes) 36 | { 37 | service.AddTransient(consumerAsyncType); 38 | //service.AddTransient(typeof(IConsumeAsync<>), consumerAsyncType); 39 | } 40 | } 41 | 42 | public static void AddEasyNetQ(this IServiceCollection service, Func getRabbitMqConneciton) 43 | { 44 | InternalInitEasyNetQ(service, getRabbitMqConneciton()); 45 | } 46 | 47 | public static void AddEasyNetQ(this IServiceCollection service, string rabbitMqConnectionString) 48 | { 49 | InternalInitEasyNetQ(service, rabbitMqConnectionString); 50 | } 51 | 52 | public static void UseEasyNetQ(this IApplicationBuilder app) 53 | { 54 | var bus = app.ApplicationServices.GetRequiredService(); 55 | var autoSubscriber = new AutoSubscriber(bus, "productor") 56 | { 57 | AutoSubscriberMessageDispatcher = app.ApplicationServices.GetRequiredService() 58 | }; 59 | autoSubscriber.Subscribe(Assembly.GetExecutingAssembly()); 60 | autoSubscriber.SubscribeAsync(Assembly.GetExecutingAssembly()); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Productor/Quartz/PublishToMqServerJob.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Threading.Tasks; 7 | using Microsoft.EntityFrameworkCore; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Logging; 10 | using Newtonsoft.Json; 11 | using Productor.Common; 12 | using Productor.Data; 13 | using Quartz; 14 | 15 | namespace Productor.Quartz 16 | { 17 | [JobDescription(Key = "PublishToMqServerJob", Group = "Productor")] 18 | [JobIntervalTrigger(Key = "PublishToMqServerJob_Trigger", Group = "Productor", IntervalInSeconds = 10, StartNow = true, IsRepeatForever = true)] 19 | //[IgnoreJobAttribute] 20 | public class PublishToMqServerJob : JobBase 21 | { 22 | private readonly ILogger _logger; 23 | private readonly IEventBus _eventBus; 24 | private readonly IServiceProvider _serviceProvider; 25 | 26 | public PublishToMqServerJob(ILogger logger, IEventBus eventBus, IServiceProvider serviceProvider) 27 | { 28 | _logger = logger; 29 | _eventBus = eventBus; 30 | _serviceProvider = serviceProvider; 31 | } 32 | 33 | protected override ILogger Logger => _logger; 34 | 35 | protected override async Task ExecuteJob(IJobExecutionContext context) 36 | { 37 | Debug.WriteLine("start"); 38 | using (var scope = _serviceProvider.CreateScope()) 39 | { 40 | var dbContext = scope.ServiceProvider.GetRequiredService(); 41 | using (var trans = await dbContext.Database.BeginTransactionAsync()) 42 | { 43 | try 44 | { 45 | var waits = await dbContext.MqMessages.Where(x => x.IsPublished == false).OrderByDescending(x => x.CreateTime).Take(10).ToListAsync(); 46 | foreach (var msg in waits) 47 | { 48 | var assemblies = AppDomain.CurrentDomain.GetAssemblies(); 49 | var assembly = assemblies.SingleOrDefault(x => x.GetName().Name == msg.MessageAssemblyName) ?? 50 | AppDomain.CurrentDomain.Load(msg.MessageAssemblyName); 51 | var type = assembly.GetType(msg.MessageClassFullName); 52 | var publishMsg = JsonConvert.DeserializeObject(msg.Body, type); 53 | _eventBus.Publish(type, publishMsg); 54 | msg.IsPublished = true; 55 | } 56 | await dbContext.SaveChangesAsync(); 57 | trans.Commit(); 58 | } 59 | catch (Exception) 60 | { 61 | trans.Rollback(); 62 | throw; 63 | } 64 | } 65 | } 66 | Debug.WriteLine("end"); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /LocalTransactionTableTest.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27428.2002 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Productor", "Productor\Productor.csproj", "{F62CB622-C141-488B-90AE-EFABE264C988}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Consumer", "Consumer\Consumer.csproj", "{E7F9A5C0-AB66-48A1-A274-B367A771B2C9}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{CD13E7D9-01E0-4C52-AD77-6966D71E84A5}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XUnitTest", "XUnitTest\XUnitTest.csproj", "{0079683F-1E62-4C11-B4AD-6063B9854A86}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Message", "Message\Message.csproj", "{20F54549-7254-4DFD-BBB2-5145B3EF37BC}" 15 | EndProject 16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{012B0734-BC3A-4CA6-BB72-0463A9FF30EC}" 17 | ProjectSection(SolutionItems) = preProject 18 | readme.txt = readme.txt 19 | EndProjectSection 20 | EndProject 21 | Global 22 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 23 | Debug|Any CPU = Debug|Any CPU 24 | Release|Any CPU = Release|Any CPU 25 | EndGlobalSection 26 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 27 | {F62CB622-C141-488B-90AE-EFABE264C988}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {F62CB622-C141-488B-90AE-EFABE264C988}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {F62CB622-C141-488B-90AE-EFABE264C988}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {F62CB622-C141-488B-90AE-EFABE264C988}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {E7F9A5C0-AB66-48A1-A274-B367A771B2C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {E7F9A5C0-AB66-48A1-A274-B367A771B2C9}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {E7F9A5C0-AB66-48A1-A274-B367A771B2C9}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {E7F9A5C0-AB66-48A1-A274-B367A771B2C9}.Release|Any CPU.Build.0 = Release|Any CPU 35 | {0079683F-1E62-4C11-B4AD-6063B9854A86}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 36 | {0079683F-1E62-4C11-B4AD-6063B9854A86}.Debug|Any CPU.Build.0 = Debug|Any CPU 37 | {0079683F-1E62-4C11-B4AD-6063B9854A86}.Release|Any CPU.ActiveCfg = Release|Any CPU 38 | {0079683F-1E62-4C11-B4AD-6063B9854A86}.Release|Any CPU.Build.0 = Release|Any CPU 39 | {20F54549-7254-4DFD-BBB2-5145B3EF37BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 40 | {20F54549-7254-4DFD-BBB2-5145B3EF37BC}.Debug|Any CPU.Build.0 = Debug|Any CPU 41 | {20F54549-7254-4DFD-BBB2-5145B3EF37BC}.Release|Any CPU.ActiveCfg = Release|Any CPU 42 | {20F54549-7254-4DFD-BBB2-5145B3EF37BC}.Release|Any CPU.Build.0 = Release|Any CPU 43 | EndGlobalSection 44 | GlobalSection(SolutionProperties) = preSolution 45 | HideSolutionNode = FALSE 46 | EndGlobalSection 47 | GlobalSection(NestedProjects) = preSolution 48 | {0079683F-1E62-4C11-B4AD-6063B9854A86} = {CD13E7D9-01E0-4C52-AD77-6966D71E84A5} 49 | EndGlobalSection 50 | GlobalSection(ExtensibilityGlobals) = postSolution 51 | SolutionGuid = {CADE280C-F0E3-44B5-9832-5AE58E2A9FBE} 52 | EndGlobalSection 53 | EndGlobal 54 | -------------------------------------------------------------------------------- /Consumer/EasyNetQ/EasyNetQExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Threading.Tasks; 6 | using Consumer.EventConsumer; 7 | using EasyNetQ; 8 | using EasyNetQ.AutoSubscribe; 9 | using Microsoft.AspNetCore.Builder; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Microsoft.Extensions.Logging; 12 | 13 | namespace Consumer.EasyNetQ 14 | { 15 | public static class EasyNetQExtension 16 | { 17 | private static void InternalInitEasyNetQ(IServiceCollection service, string rabbitMqConnection) 18 | { 19 | var bus = RabbitHutch.CreateBus(rabbitMqConnection); 20 | service.AddSingleton(bus); 21 | service.AddSingleton(serviceProvider => new ConsumerMessageDispatcher(serviceProvider, serviceProvider.GetRequiredService>())); 22 | 23 | var consumerTypes = Assembly.GetExecutingAssembly().GetTypes() 24 | .Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface) 25 | .Where(x => x.BaseType.Name == typeof(EasyNetQConsumerBase<>).Name || 26 | x.GetInterfaces().Any(t => t.Name == typeof(IConsume<>).Name)); 27 | 28 | foreach (var consumerType in consumerTypes) 29 | { 30 | service.AddTransient(consumerType); 31 | //service.AddTransient(typeof(IConsume<>), consumerType); 32 | } 33 | 34 | var consumerAsyncTypes = typeof(OrderCreatedEventConsumer).Assembly.GetTypes().Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface) 35 | .Where(x => x.GetInterfaces().Any(t => t.Name == typeof(IConsumeAsync<>).Name)); 36 | 37 | foreach (var consumerAsyncType in consumerAsyncTypes) 38 | { 39 | service.AddTransient(consumerAsyncType); 40 | //service.AddTransient(typeof(IConsumeAsync<>), consumerAsyncType); 41 | } 42 | } 43 | 44 | public static void AddEasyNetQ(this IServiceCollection service, Func getRabbitMqConneciton) 45 | { 46 | InternalInitEasyNetQ(service, getRabbitMqConneciton()); 47 | } 48 | 49 | public static void AddEasyNetQ(this IServiceCollection service, string rabbitMqConnectionString) 50 | { 51 | InternalInitEasyNetQ(service, rabbitMqConnectionString); 52 | } 53 | 54 | public static void UseEasyNetQ(this IApplicationBuilder app) 55 | { 56 | var bus = app.ApplicationServices.GetRequiredService(); 57 | var autoSubscriber = new AutoSubscriber(bus, "consumer") 58 | { 59 | AutoSubscriberMessageDispatcher = app.ApplicationServices.GetRequiredService(), 60 | GenerateSubscriptionId = x => AppDomain.CurrentDomain.FriendlyName + x.ConcreteType.Name, 61 | ConfigureSubscriptionConfiguration = x => x.WithAutoDelete(true).WithDurable(true) 62 | }; 63 | autoSubscriber.Subscribe(Assembly.GetExecutingAssembly()); 64 | autoSubscriber.SubscribeAsync(Assembly.GetExecutingAssembly()); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Productor/Migrations/20180412155138_InitProductDb.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Metadata; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | namespace Productor.Migrations 7 | { 8 | public partial class InitProductDb : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.CreateTable( 13 | name: "MqMessages", 14 | columns: table => new 15 | { 16 | Id = table.Column(type: "char(36)", nullable: false), 17 | Body = table.Column(maxLength: 4000, nullable: false), 18 | CreateTime = table.Column(nullable: false) 19 | .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), 20 | MessageAssemblyName = table.Column(maxLength: 200, nullable: false), 21 | MessageClassFullName = table.Column(maxLength: 200, nullable: false) 22 | }, 23 | constraints: table => 24 | { 25 | table.PrimaryKey("PK_MqMessages", x => x.Id); 26 | }); 27 | 28 | migrationBuilder.CreateTable( 29 | name: "OrderDetails", 30 | columns: table => new 31 | { 32 | Id = table.Column(type: "char(36)", nullable: false), 33 | CreateTime = table.Column(nullable: false) 34 | .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), 35 | OrderNo = table.Column(maxLength: 50, nullable: false), 36 | Price = table.Column(nullable: false), 37 | Quantity = table.Column(nullable: false), 38 | Sku = table.Column(maxLength: 50, nullable: false), 39 | SkuName = table.Column(maxLength: 50, nullable: false) 40 | }, 41 | constraints: table => 42 | { 43 | table.PrimaryKey("PK_OrderDetails", x => x.Id); 44 | }); 45 | 46 | migrationBuilder.CreateTable( 47 | name: "OrderHeaders", 48 | columns: table => new 49 | { 50 | Id = table.Column(type: "char(36)", nullable: false), 51 | Amount = table.Column(nullable: false), 52 | AppUser = table.Column(maxLength: 20, nullable: false), 53 | CreateTime = table.Column(nullable: false) 54 | .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), 55 | No = table.Column(maxLength: 50, nullable: false) 56 | }, 57 | constraints: table => 58 | { 59 | table.PrimaryKey("PK_OrderHeaders", x => x.Id); 60 | }); 61 | } 62 | 63 | protected override void Down(MigrationBuilder migrationBuilder) 64 | { 65 | migrationBuilder.DropTable( 66 | name: "MqMessages"); 67 | 68 | migrationBuilder.DropTable( 69 | name: "OrderDetails"); 70 | 71 | migrationBuilder.DropTable( 72 | name: "OrderHeaders"); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Productor/Migrations/20180413034406_UpdateOrderConfig.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage; 7 | using Microsoft.EntityFrameworkCore.Storage.Internal; 8 | using Productor.Data; 9 | using System; 10 | 11 | namespace Productor.Migrations 12 | { 13 | [DbContext(typeof(ProductDbContext))] 14 | [Migration("20180413034406_UpdateOrderConfig")] 15 | partial class UpdateOrderConfig 16 | { 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder 21 | .HasAnnotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn) 22 | .HasAnnotation("ProductVersion", "2.0.2-rtm-10011"); 23 | 24 | modelBuilder.Entity("Productor.Data.MqMessage", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("char(36)"); 29 | 30 | b.Property("Body") 31 | .IsRequired() 32 | .HasMaxLength(4000); 33 | 34 | b.Property("CreateTime") 35 | .ValueGeneratedOnAdd(); 36 | 37 | b.Property("MessageAssemblyName") 38 | .IsRequired() 39 | .HasMaxLength(200); 40 | 41 | b.Property("MessageClassFullName") 42 | .IsRequired() 43 | .HasMaxLength(200); 44 | 45 | b.HasKey("Id"); 46 | 47 | b.ToTable("MqMessages"); 48 | }); 49 | 50 | modelBuilder.Entity("Productor.Data.OrderDetail", b => 51 | { 52 | b.Property("Id") 53 | .ValueGeneratedOnAdd() 54 | .HasColumnType("char(36)"); 55 | 56 | b.Property("CreateTime") 57 | .ValueGeneratedOnAdd(); 58 | 59 | b.Property("ParentId") 60 | .HasColumnType("char(36)"); 61 | 62 | b.Property("Price") 63 | .HasColumnName("Price"); 64 | 65 | b.Property("Quantity") 66 | .HasColumnName("Quantity"); 67 | 68 | b.Property("Sku") 69 | .IsRequired() 70 | .HasMaxLength(50); 71 | 72 | b.Property("SkuName") 73 | .IsRequired() 74 | .HasMaxLength(50); 75 | 76 | b.HasKey("Id"); 77 | 78 | b.ToTable("OrderDetails"); 79 | }); 80 | 81 | modelBuilder.Entity("Productor.Data.OrderHeader", b => 82 | { 83 | b.Property("Id") 84 | .ValueGeneratedOnAdd() 85 | .HasColumnType("char(36)"); 86 | 87 | b.Property("Amount") 88 | .HasColumnName("Amount"); 89 | 90 | b.Property("AppUser") 91 | .IsRequired() 92 | .HasMaxLength(20); 93 | 94 | b.Property("CreateTime") 95 | .ValueGeneratedOnAdd(); 96 | 97 | b.HasKey("Id"); 98 | 99 | b.ToTable("OrderHeaders"); 100 | }); 101 | #pragma warning restore 612, 618 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /Productor/Migrations/20180414013731_SettingDeciaml.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage; 7 | using Microsoft.EntityFrameworkCore.Storage.Internal; 8 | using Productor.Data; 9 | using System; 10 | 11 | namespace Productor.Migrations 12 | { 13 | [DbContext(typeof(ProductDbContext))] 14 | [Migration("20180414013731_SettingDeciaml")] 15 | partial class SettingDeciaml 16 | { 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder 21 | .HasAnnotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn) 22 | .HasAnnotation("ProductVersion", "2.0.2-rtm-10011"); 23 | 24 | modelBuilder.Entity("Productor.Data.MqMessage", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("char(36)"); 29 | 30 | b.Property("Body") 31 | .IsRequired() 32 | .HasMaxLength(4000); 33 | 34 | b.Property("CreateTime") 35 | .ValueGeneratedOnAdd(); 36 | 37 | b.Property("MessageAssemblyName") 38 | .IsRequired() 39 | .HasMaxLength(200); 40 | 41 | b.Property("MessageClassFullName") 42 | .IsRequired() 43 | .HasMaxLength(200); 44 | 45 | b.HasKey("Id"); 46 | 47 | b.ToTable("MqMessages"); 48 | }); 49 | 50 | modelBuilder.Entity("Productor.Data.OrderDetail", b => 51 | { 52 | b.Property("Id") 53 | .ValueGeneratedOnAdd() 54 | .HasColumnType("char(36)"); 55 | 56 | b.Property("CreateTime") 57 | .ValueGeneratedOnAdd(); 58 | 59 | b.Property("ParentId") 60 | .HasColumnType("char(36)"); 61 | 62 | b.Property("Price") 63 | .HasColumnName("Price") 64 | .HasColumnType("DECIMAL(18,2)"); 65 | 66 | b.Property("Quantity") 67 | .HasColumnName("Quantity"); 68 | 69 | b.Property("Sku") 70 | .IsRequired() 71 | .HasMaxLength(50); 72 | 73 | b.Property("SkuName") 74 | .IsRequired() 75 | .HasMaxLength(50); 76 | 77 | b.HasKey("Id"); 78 | 79 | b.ToTable("OrderDetails"); 80 | }); 81 | 82 | modelBuilder.Entity("Productor.Data.OrderHeader", b => 83 | { 84 | b.Property("Id") 85 | .ValueGeneratedOnAdd() 86 | .HasColumnType("char(36)"); 87 | 88 | b.Property("Amount") 89 | .HasColumnName("Amount") 90 | .HasColumnType("DECIMAL(18,2)"); 91 | 92 | b.Property("AppUser") 93 | .IsRequired() 94 | .HasMaxLength(20); 95 | 96 | b.Property("CreateTime") 97 | .ValueGeneratedOnAdd(); 98 | 99 | b.HasKey("Id"); 100 | 101 | b.ToTable("OrderHeaders"); 102 | }); 103 | #pragma warning restore 612, 618 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /Productor/Migrations/20180412155138_InitProductDb.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage; 7 | using Microsoft.EntityFrameworkCore.Storage.Internal; 8 | using Productor.Data; 9 | using System; 10 | 11 | namespace Productor.Migrations 12 | { 13 | [DbContext(typeof(ProductDbContext))] 14 | [Migration("20180412155138_InitProductDb")] 15 | partial class InitProductDb 16 | { 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder 21 | .HasAnnotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn) 22 | .HasAnnotation("ProductVersion", "2.0.2-rtm-10011"); 23 | 24 | modelBuilder.Entity("Productor.Data.MqMessage", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("char(36)"); 29 | 30 | b.Property("Body") 31 | .IsRequired() 32 | .HasMaxLength(4000); 33 | 34 | b.Property("CreateTime") 35 | .ValueGeneratedOnAdd(); 36 | 37 | b.Property("MessageAssemblyName") 38 | .IsRequired() 39 | .HasMaxLength(200); 40 | 41 | b.Property("MessageClassFullName") 42 | .IsRequired() 43 | .HasMaxLength(200); 44 | 45 | b.HasKey("Id"); 46 | 47 | b.ToTable("MqMessages"); 48 | }); 49 | 50 | modelBuilder.Entity("Productor.Data.OrderDetail", b => 51 | { 52 | b.Property("Id") 53 | .ValueGeneratedOnAdd() 54 | .HasColumnType("char(36)"); 55 | 56 | b.Property("CreateTime") 57 | .ValueGeneratedOnAdd(); 58 | 59 | b.Property("OrderNo") 60 | .IsRequired() 61 | .HasMaxLength(50); 62 | 63 | b.Property("Price") 64 | .HasColumnName("Price"); 65 | 66 | b.Property("Quantity") 67 | .HasColumnName("Quantity"); 68 | 69 | b.Property("Sku") 70 | .IsRequired() 71 | .HasMaxLength(50); 72 | 73 | b.Property("SkuName") 74 | .IsRequired() 75 | .HasMaxLength(50); 76 | 77 | b.HasKey("Id"); 78 | 79 | b.ToTable("OrderDetails"); 80 | }); 81 | 82 | modelBuilder.Entity("Productor.Data.OrderHeader", b => 83 | { 84 | b.Property("Id") 85 | .ValueGeneratedOnAdd() 86 | .HasColumnType("char(36)"); 87 | 88 | b.Property("Amount") 89 | .HasColumnName("Amount"); 90 | 91 | b.Property("AppUser") 92 | .IsRequired() 93 | .HasMaxLength(20); 94 | 95 | b.Property("CreateTime") 96 | .ValueGeneratedOnAdd(); 97 | 98 | b.Property("No") 99 | .IsRequired() 100 | .HasMaxLength(50); 101 | 102 | b.HasKey("Id"); 103 | 104 | b.ToTable("OrderHeaders"); 105 | }); 106 | #pragma warning restore 612, 618 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /Productor/Migrations/ProductDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage; 7 | using Microsoft.EntityFrameworkCore.Storage.Internal; 8 | using Productor.Data; 9 | using System; 10 | 11 | namespace Productor.Migrations 12 | { 13 | [DbContext(typeof(ProductDbContext))] 14 | partial class ProductDbContextModelSnapshot : ModelSnapshot 15 | { 16 | protected override void BuildModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn) 21 | .HasAnnotation("ProductVersion", "2.0.2-rtm-10011"); 22 | 23 | modelBuilder.Entity("Productor.Data.MqMessage", b => 24 | { 25 | b.Property("Id") 26 | .ValueGeneratedOnAdd() 27 | .HasColumnType("char(36)"); 28 | 29 | b.Property("Body") 30 | .IsRequired() 31 | .HasMaxLength(4000); 32 | 33 | b.Property("CreateTime") 34 | .ValueGeneratedOnAdd(); 35 | 36 | b.Property("IsPublished") 37 | .ValueGeneratedOnAdd() 38 | .HasDefaultValue(false); 39 | 40 | b.Property("MessageAssemblyName") 41 | .IsRequired() 42 | .HasMaxLength(200); 43 | 44 | b.Property("MessageClassFullName") 45 | .IsRequired() 46 | .HasMaxLength(200); 47 | 48 | b.HasKey("Id"); 49 | 50 | b.ToTable("MqMessages"); 51 | }); 52 | 53 | modelBuilder.Entity("Productor.Data.OrderDetail", b => 54 | { 55 | b.Property("Id") 56 | .ValueGeneratedOnAdd() 57 | .HasColumnType("char(36)"); 58 | 59 | b.Property("CreateTime") 60 | .ValueGeneratedOnAdd(); 61 | 62 | b.Property("ParentId") 63 | .HasColumnType("char(36)"); 64 | 65 | b.Property("Price") 66 | .HasColumnName("Price") 67 | .HasColumnType("DECIMAL(18,2)"); 68 | 69 | b.Property("Quantity") 70 | .HasColumnName("Quantity"); 71 | 72 | b.Property("Sku") 73 | .IsRequired() 74 | .HasMaxLength(50); 75 | 76 | b.Property("SkuName") 77 | .IsRequired() 78 | .HasMaxLength(50); 79 | 80 | b.HasKey("Id"); 81 | 82 | b.ToTable("OrderDetails"); 83 | }); 84 | 85 | modelBuilder.Entity("Productor.Data.OrderHeader", b => 86 | { 87 | b.Property("Id") 88 | .ValueGeneratedOnAdd() 89 | .HasColumnType("char(36)"); 90 | 91 | b.Property("Amount") 92 | .HasColumnName("Amount") 93 | .HasColumnType("DECIMAL(18,2)"); 94 | 95 | b.Property("AppUser") 96 | .IsRequired() 97 | .HasMaxLength(20); 98 | 99 | b.Property("CreateTime") 100 | .ValueGeneratedOnAdd(); 101 | 102 | b.HasKey("Id"); 103 | 104 | b.ToTable("OrderHeaders"); 105 | }); 106 | #pragma warning restore 612, 618 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /Productor/Migrations/20180414032731_AddColumnToMqMessage.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage; 7 | using Microsoft.EntityFrameworkCore.Storage.Internal; 8 | using Productor.Data; 9 | using System; 10 | 11 | namespace Productor.Migrations 12 | { 13 | [DbContext(typeof(ProductDbContext))] 14 | [Migration("20180414032731_AddColumnToMqMessage")] 15 | partial class AddColumnToMqMessage 16 | { 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder 21 | .HasAnnotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn) 22 | .HasAnnotation("ProductVersion", "2.0.2-rtm-10011"); 23 | 24 | modelBuilder.Entity("Productor.Data.MqMessage", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("char(36)"); 29 | 30 | b.Property("Body") 31 | .IsRequired() 32 | .HasMaxLength(4000); 33 | 34 | b.Property("CreateTime") 35 | .ValueGeneratedOnAdd(); 36 | 37 | b.Property("IsPublished") 38 | .ValueGeneratedOnAdd() 39 | .HasDefaultValue(false); 40 | 41 | b.Property("MessageAssemblyName") 42 | .IsRequired() 43 | .HasMaxLength(200); 44 | 45 | b.Property("MessageClassFullName") 46 | .IsRequired() 47 | .HasMaxLength(200); 48 | 49 | b.HasKey("Id"); 50 | 51 | b.ToTable("MqMessages"); 52 | }); 53 | 54 | modelBuilder.Entity("Productor.Data.OrderDetail", b => 55 | { 56 | b.Property("Id") 57 | .ValueGeneratedOnAdd() 58 | .HasColumnType("char(36)"); 59 | 60 | b.Property("CreateTime") 61 | .ValueGeneratedOnAdd(); 62 | 63 | b.Property("ParentId") 64 | .HasColumnType("char(36)"); 65 | 66 | b.Property("Price") 67 | .HasColumnName("Price") 68 | .HasColumnType("DECIMAL(18,2)"); 69 | 70 | b.Property("Quantity") 71 | .HasColumnName("Quantity"); 72 | 73 | b.Property("Sku") 74 | .IsRequired() 75 | .HasMaxLength(50); 76 | 77 | b.Property("SkuName") 78 | .IsRequired() 79 | .HasMaxLength(50); 80 | 81 | b.HasKey("Id"); 82 | 83 | b.ToTable("OrderDetails"); 84 | }); 85 | 86 | modelBuilder.Entity("Productor.Data.OrderHeader", b => 87 | { 88 | b.Property("Id") 89 | .ValueGeneratedOnAdd() 90 | .HasColumnType("char(36)"); 91 | 92 | b.Property("Amount") 93 | .HasColumnName("Amount") 94 | .HasColumnType("DECIMAL(18,2)"); 95 | 96 | b.Property("AppUser") 97 | .IsRequired() 98 | .HasMaxLength(20); 99 | 100 | b.Property("CreateTime") 101 | .ValueGeneratedOnAdd(); 102 | 103 | b.HasKey("Id"); 104 | 105 | b.ToTable("OrderHeaders"); 106 | }); 107 | #pragma warning restore 612, 618 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /Productor/Quartz/QuartzExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Specialized; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Threading.Tasks; 7 | using Microsoft.AspNetCore.Builder; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Logging; 10 | using Quartz; 11 | using Quartz.Impl; 12 | using Quartz.Simpl; 13 | using Quartz.Spi; 14 | // ReSharper disable UnusedMember.Global 15 | // ReSharper disable InconsistentNaming 16 | 17 | namespace Productor.Quartz 18 | { 19 | public static class QuartzExtension 20 | { 21 | private static void InternalInitScheduer(IServiceCollection service, NameValueCollection props) 22 | { 23 | StdSchedulerFactory factory = new StdSchedulerFactory(props); 24 | 25 | // registe scheduerfactory 26 | service.AddSingleton(factory); 27 | 28 | // get a scheduler 29 | IScheduler scheduler = factory.GetScheduler().Result; 30 | 31 | // register cutomer jobfacotry 32 | service.AddSingleton(provider => new ProductorJobFactory(provider.GetService>(), provider)); 33 | 34 | // registe all jobs to Iservicecollection 35 | var jobs = typeof(JobBase).Assembly.GetTypes().Where(x => x.BaseType == typeof(JobBase) || x.GetInterfaces().Any(i => i == typeof(IJob))).Where(x => x.GetCustomAttribute() == null) 36 | .Where(x => x.IsAbstract == false); 37 | 38 | foreach (var job in jobs) 39 | { 40 | service.AddTransient(job); 41 | service.AddTransient(typeof(IJob), job); 42 | } 43 | 44 | // registe scheduer 45 | service.AddSingleton(scheduler); 46 | } 47 | 48 | public static void AddQuartz(this IServiceCollection service, NameValueCollection props) 49 | { 50 | InternalInitScheduer(service, props); 51 | } 52 | 53 | public static void AddQuartz(this IServiceCollection service) 54 | { 55 | // construct a scheduler factory 56 | NameValueCollection props = new NameValueCollection 57 | { 58 | { "quartz.serializer.type", "json" }, 59 | { "quartz.scheduler.instanceName", "ProductorScheduler" }, 60 | { "quartz.jobStore.type", "Quartz.Simpl.RAMJobStore, Quartz" }, 61 | { "quartz.threadPool.threadCount", "3" } 62 | }; 63 | InternalInitScheduer(service, props); 64 | } 65 | 66 | public static void AddQuartzUI() 67 | { 68 | 69 | } 70 | 71 | public static void UseQuartz(this IApplicationBuilder app) 72 | { 73 | var serviceProvider = app.ApplicationServices; 74 | var scheduler = serviceProvider.GetRequiredService(); 75 | var jobFactory = serviceProvider.GetRequiredService(); 76 | scheduler.JobFactory = jobFactory; 77 | scheduler.Start().Wait(); 78 | 79 | // add jobdetail with trigger to scheduler 80 | var jobs = app.ApplicationServices.GetServices(); 81 | 82 | foreach (var job in jobs) 83 | { 84 | var jobDesc = job.GetType().GetCustomAttribute(); 85 | var jobBuilder = JobBuilder.Create(job.GetType()); 86 | if (jobDesc != null) 87 | { 88 | jobBuilder.WithIdentity(jobDesc.Key, jobDesc.Group).WithDescription(jobDesc.Description); 89 | } 90 | var jobDetail = jobBuilder.Build(); 91 | 92 | ITrigger trigger; 93 | var triggerDesc = job.GetType().GetCustomAttribute(); 94 | if (triggerDesc == null) 95 | { 96 | // default trigger 97 | trigger = TriggerBuilder.Create().StartNow() 98 | .WithSimpleSchedule(x => x.WithIntervalInSeconds(60).RepeatForever()).Build(); 99 | } 100 | else 101 | { 102 | var temp = TriggerBuilder.Create().WithIdentity(triggerDesc.Key, triggerDesc.Group); 103 | if (triggerDesc.StartNow) 104 | { 105 | temp = temp.StartNow(); 106 | } 107 | if (triggerDesc.IsRepeatForever) 108 | { 109 | temp = temp.WithSimpleSchedule(x => x.WithIntervalInSeconds(triggerDesc.IntervalInSeconds) 110 | .RepeatForever()); 111 | } 112 | else 113 | { 114 | temp = temp.WithSimpleSchedule(x => x.WithIntervalInSeconds(triggerDesc.IntervalInSeconds) 115 | .WithRepeatCount(triggerDesc.RepeatCount)); 116 | } 117 | trigger = temp.Build(); 118 | } 119 | scheduler.ScheduleJob(jobDetail, trigger).Wait(); 120 | } 121 | } 122 | 123 | public static void UseQuartzUI() 124 | { 125 | 126 | } 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /Productor/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Threading.Tasks; 7 | using AspectCore.Configuration; 8 | using AspectCore.Extensions.DependencyInjection; 9 | using AspectCore.Injector; 10 | using Autofac; 11 | using AutoMapper; 12 | using Microsoft.AspNetCore.Builder; 13 | using Microsoft.AspNetCore.Hosting; 14 | using Microsoft.AspNetCore.Mvc.Filters; 15 | using Microsoft.EntityFrameworkCore; 16 | using Microsoft.Extensions.Caching.Distributed; 17 | using Microsoft.Extensions.Configuration; 18 | using Microsoft.Extensions.DependencyInjection; 19 | using Microsoft.Extensions.Logging; 20 | using Microsoft.Extensions.Options; 21 | using Newtonsoft.Json; 22 | using Newtonsoft.Json.Serialization; 23 | using Productor.Common; 24 | using Productor.Config; 25 | using Productor.Data; 26 | using Productor.EasyNetQ; 27 | using Productor.Filter; 28 | using Productor.Interceptor; 29 | using Productor.Quartz; 30 | using Productor.Service; 31 | using Productor.Swagger; 32 | using Swashbuckle.AspNetCore.Swagger; 33 | 34 | namespace Productor 35 | { 36 | public class Startup 37 | { 38 | public Startup(IHostingEnvironment env, IConfiguration configuration) 39 | { 40 | //var builder = new ConfigurationBuilder() 41 | // .SetBasePath(env.ContentRootPath) 42 | // .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 43 | // .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 44 | // .AddEnvironmentVariables(); 45 | Configuration = configuration; 46 | } 47 | 48 | public IConfiguration Configuration { get; } 49 | 50 | // This method gets called by the runtime. Use this method to add services to the container. 51 | public IServiceProvider ConfigureServices(IServiceCollection services) 52 | { 53 | services.AddAutoMapper(x => 54 | { 55 | x.AllowNullCollections = true; 56 | }); 57 | 58 | // 添加进程级别内存缓存 59 | services.AddMemoryCache(); 60 | 61 | var redisConfig = new RedisConfig() 62 | { 63 | Configuration = Configuration.GetSection("RedisConfig:Configuration").Value, 64 | InstanceName = Configuration.GetSection("RedisConfig:InstanceName").Value 65 | }; 66 | services.Configure(x => 67 | { 68 | x.Configuration = redisConfig.Configuration; 69 | x.InstanceName = redisConfig.InstanceName; 70 | }); 71 | 72 | services.AddDistributedRedisCache(options => 73 | { 74 | options.Configuration = redisConfig.Configuration; 75 | options.InstanceName = redisConfig.InstanceName; 76 | }); 77 | 78 | var mvcBuilder = services.AddMvc(x => 79 | { 80 | //x.Filters.Add(); 81 | x.Filters.Add(); 82 | x.Filters.Add(); 83 | }).AddControllersAsServices(); 84 | 85 | mvcBuilder.AddJsonOptions(x => 86 | { 87 | x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 88 | x.SerializerSettings.NullValueHandling = NullValueHandling.Include; 89 | x.SerializerSettings.DateFormatString = "yyyy-MM-dd hh:mm:ss"; 90 | }); 91 | 92 | services.AddSwagger(); 93 | 94 | services.AddDbContext(builderDb => 95 | { 96 | //var connectionStr = Configuration.GetConnectionString("Mysql"); 97 | var connectionStr = Configuration.GetConnectionString("LocalMysql"); 98 | builderDb.UseMySql(connectionStr, builder => 99 | { 100 | builder.MigrationsAssembly(typeof(ProductDbContext).Assembly.GetName().Name); 101 | }); 102 | }); 103 | 104 | 105 | //添加你的服务注册到services... 106 | //services.AddScoped(typeof(IOrderService), typeof(OrderService)); 107 | services.AddScoped(); 108 | 109 | services.AddEasyNetQ(Configuration.GetConnectionString("RabbitMq")); 110 | 111 | services.AddSingleton(); 112 | 113 | services.AddQuartz(); 114 | 115 | services.AddSingleton(); 116 | 117 | services.AddSingleton(); 118 | 119 | //将IServiceCollection的服务添加到ServiceContainer容器中 120 | var container = services.ToServiceContainer(); 121 | 122 | container.Configure(config => 123 | { 124 | config.Interceptors.AddTyped(method => method.DeclaringType.Name.EndsWith("Service")); 125 | }); 126 | 127 | return container.Build(); 128 | } 129 | 130 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 131 | public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime) 132 | { 133 | if (env.IsDevelopment()) 134 | { 135 | app.UseDeveloperExceptionPage(); 136 | } 137 | loggerFactory.AddConsole(LogLevel.Trace); 138 | loggerFactory.AddLog4Net("log4net.config"); 139 | 140 | app.UseStaticFiles(); 141 | 142 | app.UseSwaggerAll(); 143 | 144 | app.UseMvc(); 145 | 146 | app.UseEasyNetQ(); 147 | 148 | app.UseQuartz(); 149 | 150 | lifetime.ApplicationStarted.Register(() => 151 | { 152 | 153 | }); 154 | 155 | lifetime.ApplicationStopping.Register(() => 156 | { 157 | 158 | }); 159 | 160 | lifetime.ApplicationStopped.Register(() => 161 | { 162 | 163 | }); 164 | } 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /Consumer/log4net.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | -------------------------------------------------------------------------------- /Productor/log4net.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | -------------------------------------------------------------------------------- /Consumer/AutoMapper/AutoMapperExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Threading.Tasks; 6 | using AutoMapper; 7 | using Microsoft.Extensions.DependencyInjection; 8 | 9 | namespace Consumer.AutoMapper 10 | { 11 | public static class AutoMapperExtension 12 | { 13 | /// 14 | /// Use the static registration method of Mapper.Initialize. Defaults to true. 15 | /// When false, an instance of a MapperConfiguration object is registered instead. 16 | /// 17 | public static bool UseStaticRegistration { get; set; } = true; 18 | 19 | public static IServiceCollection AddAutoMapper(this IServiceCollection services, 20 | Func serviceLifetimeSelector = null, ServiceLifetime mapperLifetime = ServiceLifetime.Scoped) 21 | { 22 | return services.AddAutoMapper(null, AppDomain.CurrentDomain.GetAssemblies(), serviceLifetimeSelector, mapperLifetime); 23 | } 24 | 25 | private static readonly Action DefaultConfig = cfg => { }; 26 | 27 | public static IServiceCollection AddAutoMapper(this IServiceCollection services, params Assembly[] assemblies) 28 | => AddAutoMapperClasses(services, null, assemblies); 29 | 30 | public static IServiceCollection AddAutoMapper( 31 | this IServiceCollection services, Action additionalInitAction, params Assembly[] assemblies) 32 | => AddAutoMapperClasses(services, additionalInitAction, assemblies); 33 | 34 | public static IServiceCollection AddAutoMapper( 35 | this IServiceCollection services, Action additionalInitAction, 36 | Func serviceLifetimeSelector, ServiceLifetime mapperLifetime, 37 | params Assembly[] assemblies) 38 | => AddAutoMapperClasses(services, additionalInitAction, assemblies, serviceLifetimeSelector, mapperLifetime); 39 | 40 | public static IServiceCollection AddAutoMapper(this IServiceCollection services, Action additionalInitAction, IEnumerable assemblies, 41 | Func serviceLifetimeSelector = null, ServiceLifetime mapperLifetime = ServiceLifetime.Scoped) 42 | => AddAutoMapperClasses(services, additionalInitAction, assemblies, serviceLifetimeSelector, mapperLifetime); 43 | 44 | public static IServiceCollection AddAutoMapper(this IServiceCollection services, IEnumerable assemblies, 45 | Func serviceLifetimeSelector = null, ServiceLifetime mapperLifetime = ServiceLifetime.Scoped) 46 | => AddAutoMapperClasses(services, null, assemblies, serviceLifetimeSelector, mapperLifetime); 47 | 48 | public static IServiceCollection AddAutoMapper(this IServiceCollection services, params Type[] profileAssemblyMarkerTypes) 49 | { 50 | return AddAutoMapperClasses(services, null, profileAssemblyMarkerTypes.Select(t => t.GetTypeInfo().Assembly)); 51 | } 52 | 53 | public static IServiceCollection AddAutoMapper(this IServiceCollection services, Action additionalInitAction, 54 | Func serviceLifetimeSelector, ServiceLifetime mapperLifetime, 55 | params Type[] profileAssemblyMarkerTypes) 56 | { 57 | return AddAutoMapperClasses(services, additionalInitAction, profileAssemblyMarkerTypes.Select(t => t.GetTypeInfo().Assembly), serviceLifetimeSelector, mapperLifetime); 58 | } 59 | 60 | public static IServiceCollection AddAutoMapper(this IServiceCollection services, Action additionalInitAction, IEnumerable profileAssemblyMarkerTypes, 61 | Func serviceLifetimeSelector = null, ServiceLifetime mapperLifetime = ServiceLifetime.Scoped) 62 | { 63 | return AddAutoMapperClasses(services, additionalInitAction, profileAssemblyMarkerTypes.Select(t => t.GetTypeInfo().Assembly), serviceLifetimeSelector, mapperLifetime); 64 | } 65 | 66 | private static ServiceDescriptor CreateDescriptor(Type serviceType, ServiceLifetime lifetime) 67 | { 68 | return new ServiceDescriptor(serviceType, serviceType, lifetime); 69 | } 70 | 71 | private static IServiceCollection AddAutoMapperClasses(IServiceCollection services, Action additionalInitAction, IEnumerable assembliesToScan, 72 | Func serviceLifetimeSelector = null, ServiceLifetime mapperLifetime = ServiceLifetime.Scoped) 73 | { 74 | additionalInitAction = additionalInitAction ?? DefaultConfig; 75 | assembliesToScan = assembliesToScan as Assembly[] ?? assembliesToScan.ToArray(); 76 | 77 | var allTypes = assembliesToScan 78 | .Where(a => a.GetName().Name != nameof(AutoMapper)) 79 | .SelectMany(a => a.DefinedTypes) 80 | .ToArray(); 81 | 82 | var profiles = allTypes 83 | .Where(t => typeof(Profile).GetTypeInfo().IsAssignableFrom(t) && !t.IsAbstract) 84 | .ToArray(); 85 | 86 | 87 | void ConfigAction(IMapperConfigurationExpression cfg) 88 | { 89 | additionalInitAction(cfg); 90 | 91 | foreach (var profile in profiles.Select(t => t.AsType())) 92 | { 93 | cfg.AddProfile(profile); 94 | } 95 | } 96 | 97 | IConfigurationProvider config; 98 | if (UseStaticRegistration) 99 | { 100 | Mapper.Initialize(ConfigAction); 101 | config = Mapper.Configuration; 102 | } 103 | else 104 | { 105 | config = new MapperConfiguration(ConfigAction); 106 | } 107 | 108 | serviceLifetimeSelector = serviceLifetimeSelector ?? (typeInfo => ServiceLifetime.Transient); 109 | 110 | 111 | var openTypes = new[] 112 | { 113 | typeof(IValueResolver<,,>), 114 | typeof(IMemberValueResolver<,,,>), 115 | typeof(ITypeConverter<,>), 116 | typeof(IMappingAction<,>) 117 | }; 118 | foreach (var type in openTypes.SelectMany(openType => allTypes 119 | .Where(t => t.IsClass 120 | && !t.IsAbstract 121 | && t.AsType().ImplementsGenericInterface(openType)))) 122 | { 123 | services.Add(CreateDescriptor(type.AsType(), serviceLifetimeSelector(type))); 124 | } 125 | 126 | services.AddSingleton(config); 127 | services.Add(new ServiceDescriptor( 128 | typeof(IMapper), sp => new Mapper(sp.GetRequiredService(), sp.GetService), 129 | mapperLifetime 130 | )); 131 | return services; 132 | } 133 | 134 | private static bool ImplementsGenericInterface(this Type type, Type interfaceType) 135 | { 136 | return type.IsGenericType(interfaceType) || type.GetTypeInfo().ImplementedInterfaces.Any(@interface => @interface.IsGenericType(interfaceType)); 137 | } 138 | 139 | private static bool IsGenericType(this Type type, Type genericType) 140 | => type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == genericType; 141 | } 142 | } 143 | --------------------------------------------------------------------------------