.net core 模拟发布订阅
程序员文章站
2024-02-20 08:14:04
...
新建项目:WebApplication.Test
Nuget:
Autofac.Extensions.DependencyInjection
Newtonsoft.Json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WebApplication.Test
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())//autofac
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApplication.Test
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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)
{
services.AddControllersWithViews();
}
// ConfigureContainer is where you can register things directly
// with Autofac. This runs after ConfigureServices so the things
// here will override registrations made in ConfigureServices.
// Don't build the container; that gets done for you by the factory.
public void ConfigureContainer(ContainerBuilder builder)
{
// Register your own things directly with Autofac, like:
builder.RegisterModule(new MyApplicationModule());//autofac
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using WebApplication.Test.Models;
namespace WebApplication.Test.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IServiceProvider _serviceProvider;
public HomeController(ILogger<HomeController> logger, IServiceProvider serviceProvider)
{
_logger = logger;
_serviceProvider = serviceProvider;
}
public IActionResult Index()
{
//json 序列化CustomEvent
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new CustomEvent { Name = "MY" });
//根据type反序列化数据
var type = GetCustomType<CustomEvent>();
var customEvent = Newtonsoft.Json.JsonConvert.DeserializeObject(json, type);
//模拟发布订阅,使用事件名称作为key存储相关订阅信息
var eventName = nameof(CustomEvent);
var subscription = new Dictionary<string, List<SubscriptionInfo>> { { eventName, new List<SubscriptionInfo> { new SubscriptionInfo(typeof(CustomEvent), typeof(IEventHandler<CustomEvent>)) } } };
//创建新的生命周期执行订阅的处理程序
using (var scope = _serviceProvider.CreateScope())
{
foreach (var subscriptionInfo in subscription[eventName])
{
//订阅的处理程序已在应用启动时通过泛型方式全部注入到容器中
var handler = scope.ServiceProvider.GetRequiredService(subscriptionInfo.HandlerType);
//创建泛型精确类
var concreteType = typeof(IEventHandler<>).MakeGenericType(subscriptionInfo.EventType);
//使用反射执行处理方法
concreteType.GetMethod("Handle").Invoke(handler, new object[] { customEvent });
}
}
return View();
}
public Type GetCustomType<T>()
{
return typeof(T);
}
}
}
using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication.Test
{
public class MyApplicationModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(typeof(CustomEventHandler).Assembly)
.AsClosedTypesOf(typeof(IEventHandler<>));
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication.Test
{
public interface IEvent
{
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication.Test
{
public interface IEventHandler<in TEvent> where TEvent : IEvent
{
void Handle(TEvent @event);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication.Test
{
public class CustomEvent: IEvent
{
public string Name { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication.Test
{
public class CustomEventHandler : IEventHandler<CustomEvent>
{
private readonly IServiceProvider _serviceProvider;
public CustomEventHandler(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public void Handle(CustomEvent @event)
{
}
}
}
推荐阅读
-
.net core 模拟发布订阅
-
译 .NET Core 3.0 发布
-
向net core 3.0进击——多平台项目发布与部署
-
asp.net core系列 70 即时通迅-WebSocket+Redis发布订阅
-
记录.NET Core部署到Linux之发布项目到Linux(2)
-
发布.net core3.0 webapi +swagger
-
.NET Core单文件发布静态编译AOT CoreRT的方法详解
-
.net core 程序发布后报错误,如何配置输出详细的错误日志
-
.NET Core如何在新的项目系统中(.csproj)发布可执行文件
-
.Net Core 项目发布到Linux - CentOS 7(二)用Supervisor守护netcore进程