You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

87 lines
2.6 KiB

  1. using System;
  2. using System.Threading.Tasks;
  3. using Dapper;
  4. using DotNetCore.CAP;
  5. using DotNetCore.CAP.Messages;
  6. using Microsoft.AspNetCore.Mvc;
  7. using Microsoft.Data.SqlClient;
  8. namespace Sample.RabbitMQ.SqlServer.Controllers
  9. {
  10. [Route("api/[controller]")]
  11. public class ValuesController : Controller
  12. {
  13. private readonly ICapPublisher _capBus;
  14. public ValuesController(ICapPublisher capPublisher)
  15. {
  16. _capBus = capPublisher;
  17. }
  18. [Route("~/without/transaction")]
  19. public async Task<IActionResult> WithoutTransaction()
  20. {
  21. await _capBus.PublishAsync("sample.rabbitmq.sqlserver", new Person()
  22. {
  23. Id = 123,
  24. Name = "Bar"
  25. });
  26. return Ok();
  27. }
  28. [Route("~/adonet/transaction")]
  29. public IActionResult AdonetWithTransaction()
  30. {
  31. using (var connection = new SqlConnection(AppDbContext.ConnectionString))
  32. {
  33. using (var transaction = connection.BeginTransaction(_capBus, true))
  34. {
  35. //your business code
  36. connection.Execute("insert into test(name) values('test')", transaction: transaction);
  37. _capBus.Publish("sample.rabbitmq.sqlserver", new Person()
  38. {
  39. Id = 123,
  40. Name = "Bar"
  41. });
  42. }
  43. }
  44. return Ok();
  45. }
  46. [Route("~/ef/transaction")]
  47. public IActionResult EntityFrameworkWithTransaction([FromServices]AppDbContext dbContext)
  48. {
  49. using (dbContext.Database.BeginTransaction(_capBus, autoCommit: true))
  50. {
  51. dbContext.Persons.Add(new Person() { Name = "ef.transaction" });
  52. dbContext.SaveChanges();
  53. _capBus.Publish("sample.rabbitmq.sqlserver", new Person()
  54. {
  55. Id = 123,
  56. Name = "Bar"
  57. });
  58. }
  59. return Ok();
  60. }
  61. [NonAction]
  62. [CapSubscribe("sample.rabbitmq.sqlserver")]
  63. public void Subscriber(Person p)
  64. {
  65. Console.WriteLine($@"{DateTime.Now} Subscriber invoked, Info: {p}");
  66. }
  67. [NonAction]
  68. [CapSubscribe("sample.rabbitmq.sqlserver", Group = "group.test2")]
  69. public void Subscriber2(Person p, [FromCap]CapHeader header)
  70. {
  71. var id = header[Headers.MessageId];
  72. Console.WriteLine($@"{DateTime.Now} Subscriber invoked, Info: {p}");
  73. }
  74. }
  75. }