Asp Net Core 7 Sql Table Dependency
Enable Database Broker
SELECT is_broker_enabled FROM sys.DATABASES WHERE name = 'BikeStores';
ALTER DATABASE BikeStores SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;
Install package SqlTableDependency
dotnet add package SqlTableDependency
Create Notify Hub
public class NotificationHub : Hub{
}
Subscribe Table Dependency
public class SubscribeTableDependency{
SqlTableDependency<Table> tableDependency = null!;
readonly string connectionString;
readonly IHubContext<NotificationHub> context;
public SubscribeTableDependency(IConfiguration configuration, IHubContext<NotificationHub> context){
connectionString = configuration.GetConnectionString("Database") ?? throw new InvalidOperationException("Database Not Found");
this.context = context;
}
public void Subscribe(){
tableDependency = new SqlTableDependency<Table>(connectionString, "Table");
tableDependency.OnChanged += TableDependency_OnChanged;
tableDependency.Start();
}
async void TableDependency_OnChanged(object sender, RecordChangedEventArgs<Table> e){
if(e.ChangeType != TableDependency.SqlClient.Base.Enums.ChangeType.None){
await context.Clients.All.SendAsync("receiveTables");
}
}
}
Create Dependency SubscribeTableDependency
public static void UseTableDependency(this IApplicationBuilder builder){
var service = builder.ApplicationServices.GetRequiredService<SubscribeTableDependency>();
service.Subscribe();
}
Register Hub in Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<SubscribeTableDependency>();
builder.Services.AddSignalR();
var app = builder.Build();
app.UseStaticFiles();
app.MapHub<NotificationHub>("/notification");
app.MapDefaultControllerRoute();
app.UseTableDependency();
Client Receive Tables
var cn = new signalR.HubConnectionBuilder().withUrl('/notification').build();
cn.start().then(()=>{
console.log('Listening');
}).catch((e)=>{
console.log(e);
});
cn.on('receiveTables', ()=>{
});