Browse Source

更新源ChangeFeed 按泛型分发到不同的Service中。

CrazyIter 5 năm trước cách đây
mục cha
commit
a10446b08f

+ 1 - 0
TEAMModelOS.SDK/Context/Configuration/BaseConfigModel.cs

@@ -1,4 +1,5 @@
 using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
 
 namespace TEAMModelOS.SDK.Context.Configuration
 {

+ 1 - 1
TEAMModelOS.SDK/Module/AzureBlob/Implements/AzureBlobDBRepository.cs

@@ -30,7 +30,7 @@ namespace TEAMModelOS.SDK.Module.AzureBlob.Implements
         public AzureBlobDBRepository(IConfiguration configuration, IWebHostEnvironment env, AzureBlobOptions options, AzureBlobOptions azureBlobOptions)
         {
             Configuration = configuration;
-            BaseConfigModel.SetBaseConfig(Configuration, env.ContentRootPath, env.WebRootPath);
+           // BaseConfigModel.SetBaseConfig(Configuration, env.ContentRootPath, env.WebRootPath);
             _options = options;
             if (!string.IsNullOrEmpty(options.ConnectionString))
             {

+ 3 - 6
TEAMModelOS.SDK/Module/AzureCosmosDBV3/AzureCosmosDBV3Repository.cs

@@ -96,7 +96,7 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDBV3
         }
 
 
-        public async Task InitializeDatabase()
+        public async Task<Dictionary<string, CosmosModelInfo>> InitializeDatabase()
         {
             try
             {
@@ -187,6 +187,7 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDBV3
                     Container leaseContainer = await database.CreateContainerIfNotExistsAsync(leaseProperties, throughput: CollectionThroughput);
                     DocumentCollectionDict.TryAdd(leaseId, new CosmosModelInfo { container = leaseContainer, cache = false, monitor = false });
                 }
+                return DocumentCollectionDict;
             }
             catch (CosmosException e)
             {
@@ -194,11 +195,7 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDBV3
             }
         }
 
-        public Dictionary<string, CosmosModelInfo> GetCosmosModelInfo()
-        {
-            return this.DocumentCollectionDict;
-        }
-
+      
 
 
         private string GetPartitionKey<T>()

+ 1 - 2
TEAMModelOS.SDK/Module/AzureCosmosDBV3/IAzureCosmosDBV3Repository.cs

@@ -78,11 +78,10 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDBV3
         Task<List<T>> FindByDict<T>(Dictionary<string, object> dict, string partitionKey = null, List<string> propertys = null) where T : ID;
         Task<List<dynamic>> FindByDict(string CollectionName, Dictionary<string, object> dict, string partitionKey = null, List<string> propertys = null);
         Task<List<dynamic>> FindCountByDict(string CollectionName, Dictionary<string, object> dict, string partitionKey = null);
-        Task InitializeDatabase();
+        Task<Dictionary<string,CosmosModelInfo>> InitializeDatabase();
         Task<T>FindById<T>(string id) where T : ID;
         Task<List<T>> FindByIds<T>(List<string> ids) where T : ID;
         Task<dynamic> FindById(string CollectionName, string id);
         Task<List<dynamic>> FindByIds (string CollectionName, List<string> ids);
-        Dictionary<string, CosmosModelInfo> GetCosmosModelInfo();
     }
 }

+ 1 - 1
TEAMModelOS.Service/Models/Syllabus/SyllabusVolume.cs

@@ -10,7 +10,7 @@ using ProtoBuf;
 
 namespace TEAMModelOS.Service.Models.Syllabus
 {
-    [CosmosDB(RU = 400, Name = "SyllabusVolume")]
+    [CosmosDB(RU = 400, Name = "SyllabusVolume",Monitor =true)]
     [ProtoContract]
     public class SyllabusVolume :ID
     {

+ 22 - 38
TEAMModelOS.Service/Services/ChangeFeed/ChangeFeedInvoke.cs

@@ -1,7 +1,9 @@
 using DocumentFormat.OpenXml.Drawing;
 using Microsoft.Azure.Cosmos;
+using Microsoft.Extensions.DependencyInjection;
 using System;
 using System.Collections.Generic;
+using System.Linq;
 using System.Reflection;
 using System.Text;
 using System.Text.Json;
@@ -20,8 +22,16 @@ namespace TEAMModelOS.Service.Services.ChangeFeed
             azureCosmosDBV3Repository = _IAzureCosmosDBV3Repository;
         }
 
-        public async  Task MonitorChangeFeed() {
-           Dictionary<string,CosmosModelInfo> dict =  azureCosmosDBV3Repository.GetCosmosModelInfo();
+        public void     MonitorChangeFeed(Dictionary<string , CosmosModelInfo> dict, IServiceCollection _services) {
+            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
+            ServiceProvider serviceProvider = _services.BuildServiceProvider();  
+            List<ServiceDescriptor> services = new List<ServiceDescriptor>();
+            Type type = typeof(IChangeFeedService<>);
+            foreach (ServiceDescriptor service in _services) {
+                if (type.Name.Equals(service.ServiceType.Name)) {
+                    services.Add(service);
+                }
+            }
             foreach (string CollectionName in dict.Keys)
             {
                 if (CollectionName.Equals("AleaseContainer")) 
@@ -31,51 +41,25 @@ namespace TEAMModelOS.Service.Services.ChangeFeed
                 if (dict[CollectionName].monitor) {
                     ChangeFeedProcessor changeFeedProcessor = dict[CollectionName]
                         .container
-                        .GetChangeFeedProcessorBuilder<object>(CollectionName, async (changes, token) => await ProcessChanges(changes, CollectionName, dict[CollectionName].type))
+                        .GetChangeFeedProcessorBuilder<object>(CollectionName, async (changes, token) => 
+                        await ProcessChanges(changes,  dict[CollectionName].type , services, serviceProvider))
                         .WithInstanceName(CollectionName)
                         .WithLeaseContainer(dict["AleaseContainer"].container)
                         .Build();
-                     await changeFeedProcessor.StartAsync();
+                       changeFeedProcessor.StartAsync();
                 }
-               
             }
         }
-        /// <summary>
-        /// 获取到监听更改的数据
-        /// </summary>
-        /// <param name="changes"></param>
-        /// <param name="type"></param>
-        /// <param name="CollectionName"></param>
-        /// <returns></returns>
-        private async Task ProcessChanges(IReadOnlyCollection<object> changes,  string CollectionName,Type type)
+        private async Task ProcessChanges(IReadOnlyCollection<object> changes, Type type, 
+            List<ServiceDescriptor> services, ServiceProvider serviceProvider)
         {
-            Assembly assembly = Assembly.GetAssembly(typeof(IChangeFeedService<>));
-            Type[] types = assembly.GetTypes();
-            List<Type> list = new List<Type>();
-            foreach (Type item in types)
-            {
-                if (item.IsInterface) continue;//判断是否是接口
-                Type[] ins = item.GetInterfaces();
-                foreach (Type ty in ins)
-                {
-                    Type t = typeof(IChangeFeedService<>);
-                    t = t.MakeGenericType(type);
-                    if (ty == t)
-                    {
-                        list.Add(item);
-                    }
-                }
-            }
-            foreach (Type item in list) {
-                object obj = Activator.CreateInstance(item);//创建一个obj对象
-                MethodInfo mi = item.GetMethod("Processor");
+            foreach (ServiceDescriptor service in services) {
+                var obj = serviceProvider.GetService(service.ServiceType);
+                MethodInfo mi = service.ServiceType.GetMethod("Processor");
                 Type t = typeof(IReadOnlyCollection<>);
                 t = t.MakeGenericType(type);
-               // object objt = Activator.CreateInstance(t);
-                object bjt= JsonSerializer.Deserialize(changes.ToApiJson(), t);
-                mi.Invoke(obj, new object []{ bjt });//调用方法
-               // mi = item.GetMethod("BaseClass_VoidPublic");
-               // string s = mi.Invoke(obj, null) as string;//调用有返回值的方法,使用 as 关键字 转换返回的类型
+                object bjt = JsonSerializer.Deserialize(changes.ToApiJson(), t);
+                mi.Invoke(obj, new object[] { bjt });//调用方法
             }
         }
     }

+ 4 - 2
TEAMModelOS.Service/Services/ChangeFeed/IChangeFeedInvoke.cs

@@ -1,13 +1,15 @@
-using System;
+using Microsoft.Extensions.DependencyInjection;
+using System;
 using System.Collections.Generic;
 using System.Text;
 using System.Threading.Tasks;
 using TEAMModelOS.SDK.Context.Configuration;
+using TEAMModelOS.SDK.Module.AzureCosmosDBV3;
 
 namespace TEAMModelOS.Service.Services.ChangeFeed
 {
    public interface IChangeFeedInvoke :IBusinessService
     {
-          Task MonitorChangeFeed();
+          void MonitorChangeFeed(Dictionary<string, CosmosModelInfo> dict , IServiceCollection _services);
     }
 }

+ 2 - 1
TEAMModelOS.Service/Services/ChangeFeed/IChangeFeedService.cs

@@ -2,11 +2,12 @@
 using System.Collections.Generic;
 using System.Text;
 using System.Threading.Tasks;
+using TEAMModelOS.SDK.Context.Configuration;
 
 namespace TEAMModelOS.Service.Services.ChangeFeed
 {
     public interface IChangeFeedService<T>
     {
-        void Processor(IReadOnlyCollection<T> changes);
+        Task Processor(IReadOnlyCollection<T> changes);
     }
 }

+ 10 - 0
TEAMModelOS.Service/Services/ChangeFeed/IChangeService.cs

@@ -0,0 +1,10 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace TEAMModelOS.Service.Services.ChangeFeed
+{
+    public  interface IChangeService
+    {
+    }
+}

+ 8 - 2
TEAMModelOS.Service/Services/ChangeFeed/KnowledgeChangeFeed.cs

@@ -3,14 +3,20 @@ using System.Collections.Generic;
 using System.Text;
 using System.Threading.Tasks;
 using TEAMModelOS.SDK.Helper.Common.JsonHelper;
+using TEAMModelOS.SDK.Module.AzureCosmosDBV3;
 using TEAMModelOS.Service.Models.Syllabus;
 
 namespace TEAMModelOS.Service.Services.ChangeFeed
 {
-    public class KnowledgeChangeFeed : IChangeFeedService<Knowledge>
+    public class KnowledgeChangeFeed : IChangeFeedService<Knowledge>, IChangeService
     {
-        public void Processor(IReadOnlyCollection<Knowledge> changes)
+        private IAzureCosmosDBV3Repository cosmosDBV3Repository;
+        public KnowledgeChangeFeed(IAzureCosmosDBV3Repository azureCosmos) {
+            cosmosDBV3Repository = azureCosmos;
+        }
+        public async  Task Processor(IReadOnlyCollection<Knowledge> changes)
         {
+            //List<Knowledge> s = await cosmosDBV3Repository.FindAll<Knowledge>();
             Console.WriteLine(changes.ToApiJson());
         }
     }

+ 23 - 0
TEAMModelOS.Service/Services/ChangeFeed/SyllabusVolumeChangeFeed.cs

@@ -0,0 +1,23 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Threading.Tasks;
+using TEAMModelOS.SDK.Helper.Common.JsonHelper;
+using TEAMModelOS.SDK.Module.AzureCosmosDBV3;
+using TEAMModelOS.Service.Models.Syllabus;
+
+namespace TEAMModelOS.Service.Services.ChangeFeed
+{
+    class SyllabusVolumeChangeFeed : IChangeFeedService<SyllabusVolume>, IChangeService
+    {
+        private IAzureCosmosDBV3Repository cosmosDBV3Repository;
+        public SyllabusVolumeChangeFeed(IAzureCosmosDBV3Repository azureCosmos)
+        {
+            cosmosDBV3Repository = azureCosmos;
+        }
+        public async Task Processor(IReadOnlyCollection<SyllabusVolume> changes)
+        {
+            Console.WriteLine(changes.ToApiJson());
+        }
+    }
+}

+ 0 - 9
TEAMModelOS.Service/TEAMModelOS.Model.xml

@@ -1112,15 +1112,6 @@
             1默认为普通页面,2为题目
             </summary>
         </member>
-        <member name="M:TEAMModelOS.Service.Services.ChangeFeed.ChangeFeedInvoke.ProcessChanges(System.Collections.Generic.IReadOnlyCollection{System.Object},System.String,System.Type)">
-            <summary>
-            获取到监听更改的数据
-            </summary>
-            <param name="changes"></param>
-            <param name="type"></param>
-            <param name="CollectionName"></param>
-            <returns></returns>
-        </member>
         <member name="M:TEAMModelOS.Service.Services.Exam.Implements.HtmlAnalyzeService.ConvertTest(System.String)">
             <summary>
             解析题型

+ 15 - 0
TEAMModelOS/ServiceProviderFactory.cs

@@ -0,0 +1,15 @@
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace TEAMModelOS
+{
+    public static class ServiceProviderFactory
+    {
+         static    ServiceProviderFactory() { 
+        
+        }
+    }
+}

+ 13 - 4
TEAMModelOS/Startup.cs

@@ -15,6 +15,7 @@ using Microsoft.AspNetCore.SpaServices;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Hosting;
+using Scrutor;
 using TEAMModelOS.SDK.Context.Attributes.Azure;
 using TEAMModelOS.SDK.Context.Configuration;
 using TEAMModelOS.SDK.Context.Filter;
@@ -31,7 +32,7 @@ namespace TEAMModelOS
 {
     public class Startup
     {
-
+        private IServiceCollection _services;
         public Startup(IConfiguration configuration, IWebHostEnvironment env)
         {
             Configuration = configuration;
@@ -39,7 +40,7 @@ namespace TEAMModelOS
         }
 
         public IConfiguration Configuration { get; }
-
+      
         // This method gets called by the runtime. Use this method to add services to the container.
         public void ConfigureServices(IServiceCollection services)
         {
@@ -130,6 +131,13 @@ namespace TEAMModelOS
                .AddClasses(classes => classes.AssignableTo<IBusinessService>())
                    .AsImplementedInterfaces()
                    .WithScopedLifetime());
+            services.Scan(scan => scan.FromApplicationDependencies()
+               .AddClasses(classes => classes.AssignableTo<IChangeService>()).UsingRegistrationStrategy(RegistrationStrategy.Skip)
+                   .AsImplementedInterfaces()
+                  .WithSingletonLifetime());
+
+
+            _services = services;
         }
 
         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@@ -139,8 +147,9 @@ namespace TEAMModelOS
             {
                 app.UseDeveloperExceptionPage();
             }
-            cosmosDBV3Repository.InitializeDatabase().GetAwaiter();
-            changeFeedInvoke.MonitorChangeFeed().GetAwaiter();
+
+            Dictionary<string ,CosmosModelInfo> dict=  cosmosDBV3Repository.InitializeDatabase().Result;
+            changeFeedInvoke.MonitorChangeFeed(dict, _services);
             app.UseMiddleware<HttpGlobalExceptionInvoke>();
             //以下需要按照順序載入中間件  如果应用调用 UseStaticFiles,请将 UseStaticFiles 置于 UseRouting之前。
             app.UseStaticFiles();