-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples.html
More file actions
1360 lines (1162 loc) · 47.2 KB
/
examples.html
File metadata and controls
1360 lines (1162 loc) · 47.2 KB
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Examples - PyNurseInjector</title>
<meta name="description" content="Real-world examples and code samples for PyNurseInjector (DotNurseInjector) - see how to implement dependency injection in various scenarios.">
<link rel="stylesheet" href="css/styles.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
<nav class="navbar">
<div class="container">
<div class="nav-brand">
<i class="fas fa-syringe"></i>
<span>PyNurseInjector</span>
</div>
<ul class="nav-menu">
<li><a href="index.html">Home</a></li>
<li><a href="getting-started.html">Getting Started</a></li>
<li><a href="features.html">Features</a></li>
<li><a href="examples.html" class="active">Examples</a></li>
<li><a href="api-reference.html">API Reference</a></li>
<li><a href="https://github.com/enisn/DotNurseInjector" target="_blank"><i class="fab fa-github"></i></a></li>
</ul>
<div class="nav-toggle">
<i class="fas fa-bars"></i>
</div>
</div>
</nav>
<div class="docs-container">
<aside class="docs-sidebar">
<h3>Examples</h3>
<ul>
<li><a href="#basic-web-api">Basic Web API</a></li>
<li><a href="#repository-pattern">Repository Pattern</a></li>
<li><a href="#multi-layer">Multi-Layer Architecture</a></li>
<li><a href="#background-services">Background Services</a></li>
<li><a href="#unit-testing">Unit Testing</a></li>
<li><a href="#advanced-scenarios">Advanced Scenarios</a></li>
<li><a href="#migration-guide">Migration Guide</a></li>
</ul>
</aside>
<main class="docs-content">
<h1>Real-World Examples</h1>
<p>Learn how to use PyNurseInjector in various scenarios with these practical examples.</p>
<section id="basic-web-api">
<h2><i class="fas fa-globe"></i> Basic Web API Example</h2>
<p>A simple Web API project demonstrating basic PyNurseInjector setup.</p>
<div class="example-section">
<h3>Project Structure</h3>
<div class="code-block">
<pre><code class="language-plaintext">BookStore.Api/
├── Controllers/
│ └── BooksController.cs
├── Services/
│ ├── IBookService.cs
│ └── BookService.cs
├── Repositories/
│ ├── IBookRepository.cs
│ └── BookRepository.cs
├── Models/
│ └── Book.cs
└── Program.cs</code></pre>
</div>
<h3>Program.cs</h3>
<div class="code-block">
<pre><code class="language-csharp">using DotNurse.Injector;
using DotNurse.Injector.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
// Enable property injection
builder.Host.UseDotNurseInjector();
// Add services
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Register all services and repositories
builder.Services.AddServicesFrom("BookStore.Api.Services");
builder.Services.AddServicesFrom("BookStore.Api.Repositories", ServiceLifetime.Scoped);
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();</code></pre>
</div>
<h3>Models/Book.cs</h3>
<div class="code-block">
<pre><code class="language-csharp">namespace BookStore.Api.Models;
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string ISBN { get; set; }
public decimal Price { get; set; }
public DateTime PublishedDate { get; set; }
}</code></pre>
</div>
<h3>Services/IBookService.cs & BookService.cs</h3>
<div class="code-block">
<pre><code class="language-csharp">namespace BookStore.Api.Services;
public interface IBookService
{
Task<IEnumerable<Book>> GetAllBooksAsync();
Task<Book> GetBookByIdAsync(int id);
Task<Book> CreateBookAsync(Book book);
Task<Book> UpdateBookAsync(int id, Book book);
Task DeleteBookAsync(int id);
}
public class BookService : IBookService
{
[InjectService]
private readonly IBookRepository bookRepository;
[InjectService]
private readonly ILogger<BookService> logger;
public async Task<IEnumerable<Book>> GetAllBooksAsync()
{
logger.LogInformation("Fetching all books");
return await bookRepository.GetAllAsync();
}
public async Task<Book> GetBookByIdAsync(int id)
{
logger.LogInformation("Fetching book with ID: {BookId}", id);
var book = await bookRepository.GetByIdAsync(id);
if (book == null)
{
logger.LogWarning("Book with ID {BookId} not found", id);
throw new KeyNotFoundException($"Book with ID {id} not found");
}
return book;
}
public async Task<Book> CreateBookAsync(Book book)
{
logger.LogInformation("Creating new book: {Title}", book.Title);
return await bookRepository.CreateAsync(book);
}
public async Task<Book> UpdateBookAsync(int id, Book book)
{
logger.LogInformation("Updating book with ID: {BookId}", id);
book.Id = id;
return await bookRepository.UpdateAsync(book);
}
public async Task DeleteBookAsync(int id)
{
logger.LogInformation("Deleting book with ID: {BookId}", id);
await bookRepository.DeleteAsync(id);
}
}</code></pre>
</div>
<h3>Controllers/BooksController.cs</h3>
<div class="code-block">
<pre><code class="language-csharp">namespace BookStore.Api.Controllers;
[ApiController]
[Route("api/[controller]")]
public class BooksController : ControllerBase
{
[InjectService]
public IBookService BookService { get; private set; }
[HttpGet]
public async Task<ActionResult<IEnumerable<Book>>> GetBooks()
{
var books = await BookService.GetAllBooksAsync();
return Ok(books);
}
[HttpGet("{id}")]
public async Task<ActionResult<Book>> GetBook(int id)
{
try
{
var book = await BookService.GetBookByIdAsync(id);
return Ok(book);
}
catch (KeyNotFoundException)
{
return NotFound();
}
}
[HttpPost]
public async Task<ActionResult<Book>> CreateBook(Book book)
{
var createdBook = await BookService.CreateBookAsync(book);
return CreatedAtAction(nameof(GetBook), new { id = createdBook.Id }, createdBook);
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateBook(int id, Book book)
{
try
{
await BookService.UpdateBookAsync(id, book);
return NoContent();
}
catch (KeyNotFoundException)
{
return NotFound();
}
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteBook(int id)
{
try
{
await BookService.DeleteBookAsync(id);
return NoContent();
}
catch (KeyNotFoundException)
{
return NotFound();
}
}
}</code></pre>
</div>
</div>
</section>
<section id="repository-pattern">
<h2><i class="fas fa-database"></i> Repository Pattern Example</h2>
<p>Implementing a generic repository pattern with PyNurseInjector.</p>
<div class="example-section">
<h3>Generic Repository Interface</h3>
<div class="code-block">
<pre><code class="language-csharp">namespace MyApp.Core.Repositories;
public interface IRepository<T> where T : class
{
Task<T> GetByIdAsync(int id);
Task<IEnumerable<T>> GetAllAsync();
Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate);
Task<T> AddAsync(T entity);
Task UpdateAsync(T entity);
Task DeleteAsync(T entity);
Task<int> SaveChangesAsync();
}
public interface IUserRepository : IRepository<User>
{
Task<User> GetByEmailAsync(string email);
Task<IEnumerable<User>> GetActiveUsersAsync();
}
public interface IProductRepository : IRepository<Product>
{
Task<IEnumerable<Product>> GetByCategoryAsync(string category);
Task<IEnumerable<Product>> GetTopSellingAsync(int count);
}</code></pre>
</div>
<h3>Base Repository Implementation</h3>
<div class="code-block">
<pre><code class="language-csharp">namespace MyApp.Infrastructure.Repositories;
public abstract class BaseRepository<T> : IRepository<T> where T : class
{
[InjectService]
protected AppDbContext Context { get; private set; }
[InjectService]
protected ILogger<BaseRepository<T>> Logger { get; private set; }
protected DbSet<T> DbSet => Context.Set<T>();
public virtual async Task<T> GetByIdAsync(int id)
{
return await DbSet.FindAsync(id);
}
public virtual async Task<IEnumerable<T>> GetAllAsync()
{
return await DbSet.ToListAsync();
}
public virtual async Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate)
{
return await DbSet.Where(predicate).ToListAsync();
}
public virtual async Task<T> AddAsync(T entity)
{
await DbSet.AddAsync(entity);
return entity;
}
public virtual async Task UpdateAsync(T entity)
{
DbSet.Update(entity);
}
public virtual async Task DeleteAsync(T entity)
{
DbSet.Remove(entity);
}
public async Task<int> SaveChangesAsync()
{
return await Context.SaveChangesAsync();
}
}</code></pre>
</div>
<h3>Specific Repository Implementations</h3>
<div class="code-block">
<pre><code class="language-csharp">namespace MyApp.Infrastructure.Repositories;
[RegisterAs(typeof(IUserRepository))]
[ServiceLifeTime(ServiceLifetime.Scoped)]
public class UserRepository : BaseRepository<User>, IUserRepository
{
public async Task<User> GetByEmailAsync(string email)
{
Logger.LogDebug("Getting user by email: {Email}", email);
return await DbSet.FirstOrDefaultAsync(u => u.Email == email);
}
public async Task<IEnumerable<User>> GetActiveUsersAsync()
{
return await DbSet
.Where(u => u.IsActive && !u.IsDeleted)
.OrderBy(u => u.Name)
.ToListAsync();
}
}
[RegisterAs(typeof(IProductRepository))]
[ServiceLifeTime(ServiceLifetime.Scoped)]
public class ProductRepository : BaseRepository<Product>, IProductRepository
{
public async Task<IEnumerable<Product>> GetByCategoryAsync(string category)
{
return await DbSet
.Where(p => p.Category == category && p.IsAvailable)
.ToListAsync();
}
public async Task<IEnumerable<Product>> GetTopSellingAsync(int count)
{
return await DbSet
.OrderByDescending(p => p.SalesCount)
.Take(count)
.ToListAsync();
}
}</code></pre>
</div>
<h3>Registration</h3>
<div class="code-block">
<pre><code class="language-csharp">// In Program.cs
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Register all repositories that inherit from BaseRepository
builder.Services.AddServicesFrom("MyApp.Infrastructure.Repositories", ServiceLifetime.Scoped, options =>
{
options.ImplementationBase = typeof(BaseRepository<>);
});</code></pre>
</div>
</div>
</section>
<section id="multi-layer">
<h2><i class="fas fa-layer-group"></i> Multi-Layer Architecture</h2>
<p>Complete example of a multi-layered application using PyNurseInjector.</p>
<div class="example-section">
<h3>Solution Structure</h3>
<div class="code-block">
<pre><code class="language-plaintext">MyEcommerce/
├── MyEcommerce.Domain/ # Domain entities and interfaces
│ ├── Entities/
│ ├── Interfaces/
│ └── ValueObjects/
├── MyEcommerce.Application/ # Business logic and DTOs
│ ├── Services/
│ ├── DTOs/
│ └── Mappings/
├── MyEcommerce.Infrastructure/ # Data access and external services
│ ├── Repositories/
│ ├── Services/
│ └── DbContext/
└── MyEcommerce.Api/ # Web API layer
├── Controllers/
├── Middleware/
└── Program.cs</code></pre>
</div>
<h3>Domain Layer</h3>
<div class="code-block">
<pre><code class="language-csharp">// MyEcommerce.Domain/Interfaces/IOrderService.cs
namespace MyEcommerce.Domain.Interfaces;
public interface IOrderService
{
Task<Order> CreateOrderAsync(CreateOrderDto orderDto);
Task<Order> GetOrderByIdAsync(int orderId);
Task<bool> ProcessPaymentAsync(int orderId, PaymentDto paymentDto);
Task UpdateOrderStatusAsync(int orderId, OrderStatus status);
}
// MyEcommerce.Domain/Interfaces/IInventoryService.cs
public interface IInventoryService
{
Task<bool> CheckAvailabilityAsync(int productId, int quantity);
Task ReserveStockAsync(int productId, int quantity);
Task ReleaseStockAsync(int productId, int quantity);
}</code></pre>
</div>
<h3>Application Layer</h3>
<div class="code-block">
<pre><code class="language-csharp">// MyEcommerce.Application/Services/OrderService.cs
namespace MyEcommerce.Application.Services;
[RegisterAs(typeof(IOrderService))]
[ServiceLifeTime(ServiceLifetime.Scoped)]
public class OrderService : IOrderService
{
[InjectService] private IOrderRepository orderRepository;
[InjectService] private IProductRepository productRepository;
[InjectService] private IInventoryService inventoryService;
[InjectService] private IPaymentService paymentService;
[InjectService] private INotificationService notificationService;
[InjectService] private ILogger<OrderService> logger;
public async Task<Order> CreateOrderAsync(CreateOrderDto orderDto)
{
logger.LogInformation("Creating order for customer {CustomerId}", orderDto.CustomerId);
// Validate products availability
foreach (var item in orderDto.Items)
{
var isAvailable = await inventoryService.CheckAvailabilityAsync(item.ProductId, item.Quantity);
if (!isAvailable)
{
throw new BusinessException($"Product {item.ProductId} is not available");
}
}
// Reserve inventory
foreach (var item in orderDto.Items)
{
await inventoryService.ReserveStockAsync(item.ProductId, item.Quantity);
}
// Create order
var order = new Order
{
CustomerId = orderDto.CustomerId,
OrderDate = DateTime.UtcNow,
Status = OrderStatus.Pending,
Items = orderDto.Items.Select(i => new OrderItem
{
ProductId = i.ProductId,
Quantity = i.Quantity,
Price = i.Price
}).ToList()
};
await orderRepository.AddAsync(order);
await orderRepository.SaveChangesAsync();
// Send notification
await notificationService.SendOrderConfirmationAsync(order);
return order;
}
public async Task<bool> ProcessPaymentAsync(int orderId, PaymentDto paymentDto)
{
var order = await orderRepository.GetByIdAsync(orderId);
if (order == null)
{
throw new NotFoundException($"Order {orderId} not found");
}
var paymentResult = await paymentService.ProcessPaymentAsync(order, paymentDto);
if (paymentResult.Success)
{
order.Status = OrderStatus.Paid;
order.PaymentId = paymentResult.TransactionId;
await orderRepository.UpdateAsync(order);
await orderRepository.SaveChangesAsync();
await notificationService.SendPaymentConfirmationAsync(order);
}
return paymentResult.Success;
}
}</code></pre>
</div>
<h3>Infrastructure Layer</h3>
<div class="code-block">
<pre><code class="language-csharp">// MyEcommerce.Infrastructure/Services/EmailNotificationService.cs
namespace MyEcommerce.Infrastructure.Services;
[RegisterAs(typeof(INotificationService))]
[ServiceLifeTime(ServiceLifetime.Singleton)]
public class EmailNotificationService : INotificationService
{
[InjectService] private IEmailSender emailSender;
[InjectService] private ITemplateEngine templateEngine;
[InjectService] private IConfiguration configuration;
public async Task SendOrderConfirmationAsync(Order order)
{
var template = await templateEngine.RenderAsync("OrderConfirmation", order);
var email = new EmailMessage
{
To = order.Customer.Email,
Subject = $"Order Confirmation - #{order.Id}",
Body = template
};
await emailSender.SendAsync(email);
}
public async Task SendPaymentConfirmationAsync(Order order)
{
var template = await templateEngine.RenderAsync("PaymentConfirmation", order);
var email = new EmailMessage
{
To = order.Customer.Email,
Subject = $"Payment Confirmation - Order #{order.Id}",
Body = template
};
await emailSender.SendAsync(email);
}
}</code></pre>
</div>
<h3>API Layer Configuration</h3>
<div class="code-block">
<pre><code class="language-csharp">// MyEcommerce.Api/Program.cs
var builder = WebApplication.CreateBuilder(args);
// Enable property injection
builder.Host.UseDotNurseInjector();
// Add services
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Register services from all layers
builder.Services.AddServicesFrom("MyEcommerce.Application.Services", ServiceLifetime.Scoped);
builder.Services.AddServicesFrom("MyEcommerce.Infrastructure.Repositories", ServiceLifetime.Scoped);
builder.Services.AddServicesFrom("MyEcommerce.Infrastructure.Services", ServiceLifetime.Singleton);
// Add AutoMapper
builder.Services.AddAutoMapper(typeof(MappingProfile));
// Add authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// JWT configuration
});
var app = builder.Build();
// Middleware pipeline
app.UseExceptionHandler("/error");
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();</code></pre>
</div>
</div>
</section>
<section id="background-services">
<h2><i class="fas fa-cogs"></i> Background Services Example</h2>
<p>Using PyNurseInjector with hosted services and background tasks.</p>
<div class="example-section">
<h3>Order Processing Background Service</h3>
<div class="code-block">
<pre><code class="language-csharp">namespace MyApp.Services.Background;
[RegisterAs(typeof(IHostedService))]
[ServiceLifeTime(ServiceLifetime.Singleton)]
public class OrderProcessingService : BackgroundService
{
[InjectService] private IServiceProvider serviceProvider;
[InjectService] private ILogger<OrderProcessingService> logger;
[InjectService] private IConfiguration configuration;
private readonly TimeSpan _period;
public OrderProcessingService()
{
_period = TimeSpan.FromMinutes(5); // Process every 5 minutes
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation("Order Processing Service is starting.");
using PeriodicTimer timer = new(_period);
while (!stoppingToken.IsCancellationRequested &&
await timer.WaitForNextTickAsync(stoppingToken))
{
await ProcessPendingOrdersAsync(stoppingToken);
}
}
private async Task ProcessPendingOrdersAsync(CancellationToken cancellationToken)
{
try
{
using var scope = serviceProvider.CreateScope();
// Resolve scoped services
var orderService = scope.ServiceProvider.GetRequiredService<IOrderService>();
var orderRepository = scope.ServiceProvider.GetRequiredService<IOrderRepository>();
var pendingOrders = await orderRepository.GetPendingOrdersAsync();
logger.LogInformation("Processing {Count} pending orders", pendingOrders.Count());
foreach (var order in pendingOrders)
{
if (cancellationToken.IsCancellationRequested)
break;
try
{
await orderService.ProcessOrderAsync(order.Id);
logger.LogInformation("Successfully processed order {OrderId}", order.Id);
}
catch (Exception ex)
{
logger.LogError(ex, "Error processing order {OrderId}", order.Id);
}
}
}
catch (Exception ex)
{
logger.LogError(ex, "Error in order processing service");
}
}
}</code></pre>
</div>
<h3>Email Queue Service</h3>
<div class="code-block">
<pre><code class="language-csharp">[RegisterAs(typeof(IHostedService))]
[ServiceLifeTime(ServiceLifetime.Singleton)]
public class EmailQueueService : BackgroundService
{
[InjectService] private IEmailQueue emailQueue;
[InjectService] private IEmailSender emailSender;
[InjectService] private ILogger<EmailQueueService> logger;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation("Email Queue Service is starting.");
while (!stoppingToken.IsCancellationRequested)
{
try
{
var email = await emailQueue.DequeueAsync(stoppingToken);
if (email != null)
{
await SendEmailWithRetryAsync(email, stoppingToken);
}
else
{
// No emails in queue, wait a bit
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
catch (OperationCanceledException)
{
// Service is stopping
break;
}
catch (Exception ex)
{
logger.LogError(ex, "Error in email queue service");
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
}
}
private async Task SendEmailWithRetryAsync(EmailMessage email, CancellationToken cancellationToken)
{
const int maxRetries = 3;
var retryCount = 0;
while (retryCount < maxRetries)
{
try
{
await emailSender.SendAsync(email);
logger.LogInformation("Email sent successfully to {Recipient}", email.To);
break;
}
catch (Exception ex)
{
retryCount++;
logger.LogWarning(ex, "Failed to send email (attempt {Attempt}/{MaxAttempts})",
retryCount, maxRetries);
if (retryCount >= maxRetries)
{
logger.LogError("Failed to send email after {MaxAttempts} attempts", maxRetries);
// Could move to dead letter queue here
break;
}
await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, retryCount)), cancellationToken);
}
}
}
}</code></pre>
</div>
</div>
</section>
<section id="unit-testing">
<h2><i class="fas fa-vial"></i> Unit Testing with PyNurseInjector</h2>
<p>How to write unit tests for services using PyNurseInjector.</p>
<div class="example-section">
<h3>Test Setup</h3>
<div class="code-block">
<pre><code class="language-csharp">using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Moq;
public class ServiceTestBase : IDisposable
{
protected IServiceProvider ServiceProvider { get; }
protected IServiceCollection Services { get; }
public ServiceTestBase()
{
Services = new ServiceCollection();
// Add logging
Services.AddLogging(builder => builder.AddDebug());
// Register test services
RegisterTestServices();
// Build service provider
ServiceProvider = Services.BuildServiceProvider();
}
protected virtual void RegisterTestServices()
{
// Override in derived classes
}
protected T GetService<T>() where T : notnull
{
return ServiceProvider.GetRequiredService<T>();
}
public void Dispose()
{
if (ServiceProvider is IDisposable disposable)
{
disposable.Dispose();
}
}
}</code></pre>
</div>
<h3>Testing Services with Mocked Dependencies</h3>
<div class="code-block">
<pre><code class="language-csharp">public class BookServiceTests : ServiceTestBase
{
private readonly Mock<IBookRepository> _bookRepositoryMock;
private readonly Mock<ILogger<BookService>> _loggerMock;
public BookServiceTests()
{
_bookRepositoryMock = new Mock<IBookRepository>();
_loggerMock = new Mock<ILogger<BookService>>();
}
protected override void RegisterTestServices()
{
// Register mocks
Services.AddSingleton(_bookRepositoryMock.Object);
Services.AddSingleton(_loggerMock.Object);
// Register service under test
Services.AddTransient<BookService>();
// Enable property injection for tests
Services.AddSingleton<IServiceProvider>(provider =>
new DotNurseServiceProvider(provider));
}
[Fact]
public async Task GetBookByIdAsync_WhenBookExists_ReturnsBook()
{
// Arrange
var bookId = 1;
var expectedBook = new Book
{
Id = bookId,
Title = "Test Book",
Author = "Test Author"
};
_bookRepositoryMock
.Setup(x => x.GetByIdAsync(bookId))
.ReturnsAsync(expectedBook);
var bookService = GetService<BookService>();
// Act
var result = await bookService.GetBookByIdAsync(bookId);
// Assert
Assert.NotNull(result);
Assert.Equal(expectedBook.Id, result.Id);
Assert.Equal(expectedBook.Title, result.Title);
_bookRepositoryMock.Verify(x => x.GetByIdAsync(bookId), Times.Once);
}
[Fact]
public async Task GetBookByIdAsync_WhenBookNotFound_ThrowsException()
{
// Arrange
var bookId = 999;
_bookRepositoryMock
.Setup(x => x.GetByIdAsync(bookId))
.ReturnsAsync((Book)null);
var bookService = GetService<BookService>();
// Act & Assert
await Assert.ThrowsAsync<KeyNotFoundException>(
() => bookService.GetBookByIdAsync(bookId));
_loggerMock.Verify(
x => x.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((o, t) => o.ToString().Contains($"Book with ID {bookId} not found")),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception, string>>()),
Times.Once);
}
}</code></pre>
</div>
<h3>Integration Testing</h3>
<div class="code-block">
<pre><code class="language-csharp">public class BookApiIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
private readonly HttpClient _client;
public BookApiIntegrationTests(WebApplicationFactory<Program> factory)
{
_factory = factory.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
// Remove real database
var descriptor = services.SingleOrDefault(
d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
if (descriptor != null)
{
services.Remove(descriptor);
}
// Add in-memory database for testing
services.AddDbContext<AppDbContext>(options =>
{
options.UseInMemoryDatabase("TestDb");
});
// Ensure PyNurseInjector registrations
services.AddServicesFrom("BookStore.Api.Services");
services.AddServicesFrom("BookStore.Api.Repositories");
});
});
_client = _factory.CreateClient();
}
[Fact]
public async Task GetBooks_ReturnsSuccessAndCorrectContentType()
{
// Act
var response = await _client.GetAsync("/api/books");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal("application/json; charset=utf-8",
response.Content.Headers.ContentType.ToString());
}
[Fact]
public async Task CreateBook_WithValidData_ReturnsCreatedBook()
{
// Arrange
var newBook = new Book
{
Title = "Integration Test Book",
Author = "Test Author",
ISBN = "123-456-789",
Price = 29.99m
};
var json = JsonSerializer.Serialize(newBook);
var content = new StringContent(json, Encoding.UTF8, "application/json");
// Act
var response = await _client.PostAsync("/api/books", content);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var responseContent = await response.Content.ReadAsStringAsync();
var createdBook = JsonSerializer.Deserialize<Book>(responseContent);
Assert.NotNull(createdBook);
Assert.Equal(newBook.Title, createdBook.Title);
Assert.True(createdBook.Id > 0);
}
}</code></pre>
</div>
</div>
</section>
<section id="advanced-scenarios">
<h2><i class="fas fa-rocket"></i> Advanced Scenarios</h2>
<p>Complex use cases and advanced patterns with PyNurseInjector.</p>
<div class="example-section">
<h3>Decorator Pattern</h3>
<div class="code-block">
<pre><code class="language-csharp">// Base service interface
public interface ICacheService
{
Task<T> GetAsync<T>(string key);
Task SetAsync<T>(string key, T value, TimeSpan? expiry = null);
}
// Primary implementation
[RegisterAs(typeof(ICacheService))]
public class RedisCacheService : ICacheService
{
[InjectService] private IConnectionMultiplexer redis;
public async Task<T> GetAsync<T>(string key)