-
-
Notifications
You must be signed in to change notification settings - Fork 558
Expand file tree
/
Copy pathMartenServiceCollectionExtensions.cs
More file actions
1206 lines (1068 loc) · 51.8 KB
/
Copy pathMartenServiceCollectionExtensions.cs
File metadata and controls
1206 lines (1068 loc) · 51.8 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
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using JasperFx;
using JasperFx.Documents;
using JasperFx.MultiTenancy;
using JasperFx.CommandLine;
using JasperFx.CommandLine.Descriptions;
using JasperFx.Core.Reflection;
using JasperFx.Events;
using JasperFx.Events.Daemon;
using JasperFx.Events.Projections;
using JasperFx.Events.Subscriptions;
using Marten.Events.Daemon.Coordination;
using Marten.Events.Projections;
using Marten.Internal;
using Marten.Schema;
using Marten.Services;
using Marten.Sessions;
using Marten.Subscriptions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Npgsql;
using Weasel.Core.Migrations;
using Weasel.Core.MultiTenancy;
using System.Diagnostics.CodeAnalysis;
namespace Marten;
[UnconditionalSuppressMessage("Trimming", "IL2026",
Justification = "Class-level: consumes RUC-annotated members (ISerializer, JasperFx.Events aggregator graph, CloseAndBuildAs / GenericFactoryCache fallbacks, FastExpressionCompiler). Document/event/projection types flow in from StoreOptions / Schema.For<T>() / projection registration and are preserved per the AOT publishing guide; AOT consumers supply a source-generator-backed serializer + pre-generated codegen artifacts.")]
[UnconditionalSuppressMessage("Trimming", "IL2087",
Justification = "Class-level: generic method/type argument flows reflective Type values into a DAM-annotated target. Source preserved at the registration boundary.")]
[UnconditionalSuppressMessage("Trimming", "IL2091",
Justification = "Class-level: generic type argument doesn't carry the DAM annotation of its target. The argument types flow in from StoreOptions / projection-registration on the caller side and are preserved by the trimmer at that boundary.")]
public static class MartenServiceCollectionExtensions
{
/// <summary>
/// Apply additional configuration to a Marten DocumentStore. This is applied *after*
/// AddMarten(), but before the DocumentStore is initialized
/// </summary>
/// <param name="services"></param>
/// <param name="configure"></param>
/// <returns></returns>
public static IServiceCollection ConfigureMartenWithServices<T>(this IServiceCollection services)
where T : class, IAsyncConfigureMarten
{
services.EnsureAsyncConfigureMartenApplicationIsRegistered();
services.AddSingleton<IAsyncConfigureMarten, T>();
return services;
}
/// <summary>
/// Apply additional configuration to a Marten DocumentStore. This is applied *after*
/// AddMarten(), but before the DocumentStore is initialized
/// </summary>
/// <param name="services"></param>
/// <param name="configure"></param>
/// <returns></returns>
public static IServiceCollection ConfigureMarten(this IServiceCollection services,
Action<StoreOptions> configure)
{
return services.ConfigureMarten((s, opts) => configure(opts));
}
/// <summary>
/// Apply additional configuration to a Marten DocumentStore. This is applied *after*
/// AddMarten(), but before the DocumentStore is initialized
/// </summary>
/// <param name="services"></param>
/// <param name="configure"></param>
/// <returns></returns>
public static IServiceCollection ConfigureMarten(this IServiceCollection services,
Action<IServiceProvider, StoreOptions> configure)
{
var configureMarten = new LambdaConfigureMarten(configure);
services.AddSingleton<IConfigureMarten>(configureMarten);
return services;
}
/// <summary>
/// Apply additional configuration to a Marten DocumentStore of type "T". This is applied *after*
/// AddMartenStore<T>(), but before the actual DocumentStore for "T" is initialized
/// </summary>
/// <param name="services"></param>
/// <param name="configure"></param>
/// <returns></returns>
public static IServiceCollection ConfigureMarten<T>(this IServiceCollection services,
Action<IServiceProvider, StoreOptions> configure) where T : IDocumentStore
{
var configureMarten = new LambdaConfigureMarten<T>(configure);
services.AddSingleton<IConfigureMarten<T>>(configureMarten);
return services;
}
/// <summary>
/// Apply additional configuration to a Marten DocumentStore of type "T". This is applied *after*
/// AddMartenStore<T>(), but before the actual DocumentStore for "T" is initialized
/// </summary>
/// <param name="services"></param>
/// <param name="configure"></param>
/// <returns></returns>
public static IServiceCollection ConfigureMarten<T>(this IServiceCollection services,
Action<StoreOptions> configure) where T : IDocumentStore
{
var configureMarten = new LambdaConfigureMarten<T>((s, opts) => configure(opts));
services.AddSingleton<IConfigureMarten<T>>(configureMarten);
return services;
}
/// <summary>
/// Add Marten IDocumentStore, IDocumentSession, and IQuerySession service registrations
/// to your application with the given Postgresql connection string and Marten
/// defaults
/// </summary>
/// <remarks>
/// You need to configure connection settings through DI, e.g. by calling `UseNpgsqlDataSource`
/// and configuring `NpqsqlDataSource` with `AddNpgsqlDataSource` from `Npgsql.DependencyInjection`
/// </remarks>
/// <param name="services"></param>
/// <returns></returns>
public static MartenConfigurationExpression AddMarten(this IServiceCollection services)
{
return services.AddMarten(new StoreOptions());
}
/// <summary>
/// Add Marten IDocumentStore, IDocumentSession, and IQuerySession service registrations
/// to your application with the given Postgresql connection string and Marten
/// defaults
/// </summary>
/// <param name="services"></param>
/// <param name="connectionString">The connection string to your application's Postgresql database</param>
/// <returns></returns>
public static MartenConfigurationExpression AddMarten(this IServiceCollection services, string connectionString)
{
var options = new StoreOptions();
options.Connection(connectionString);
return services.AddMarten(options);
}
/// <summary>
/// Add Marten IDocumentStore, IDocumentSession, and IQuerySession service registrations
/// to your application using the configured StoreOptions
/// </summary>
/// <param name="services"></param>
/// <param name="options">The Marten configuration for this application</param>
/// <returns></returns>
public static MartenConfigurationExpression AddMarten(
this IServiceCollection services,
StoreOptions options
)
{
services.AddMarten(s => options);
// #4598 / jasperfx#413: when the configured tenancy is a dynamic source
// (MasterTableTenancy or ShardedTenancy as of #4598), register it as
// IDynamicTenantSource<string> so a store-agnostic admin tool (e.g.
// CritterWatch) can resolve it via GetServices without referencing
// concrete Marten tenancy types. Conditional so non-dynamic stores
// (DefaultTenancy / StaticMultiTenant) keep GetServices empty — the
// graceful-no-op behavior the consumer relies on.
//
// Probed safely: `options.Tenancy` throws if no tenancy is configured yet
// (e.g. when the caller uses the AddMarten() + later UseNpgsqlDataSource()
// pattern). Dynamic tenancies are always set inside the StoreOptions
// configure callback before AddMarten returns, so a not-yet-configured
// store is by construction not dynamic and the registration is correctly
// skipped.
if (TryGetDynamicTenantSource(options) is not null)
{
services.AddSingleton<IDynamicTenantSource<string>>(s =>
(IDynamicTenantSource<string>)s.GetRequiredService<IDocumentStore>().As<DocumentStore>().Tenancy);
}
return new MartenConfigurationExpression(services, options);
}
private static IDynamicTenantSource<string>? TryGetDynamicTenantSource(StoreOptions options)
{
try
{
return options.Tenancy as IDynamicTenantSource<string>;
}
catch (InvalidOperationException)
{
// No tenancy configured yet — the caller is on the AddMarten() +
// UseNpgsqlDataSource() flow, which only ever lands on DefaultTenancy
// (not dynamic). Safe to treat as "not a dynamic source".
return null;
}
}
/// <summary>
/// Add Marten IDocumentStore, IDocumentSession, and IQuerySession service registrations
/// to your application by configuring a StoreOptions using services in your DI container
/// </summary>
/// <param name="optionSource">Func that will build out a StoreOptions with the applications IServiceProvider as the input</param>
/// <returns></returns>
public static MartenConfigurationExpression AddMarten(
this IServiceCollection services,
Func<IServiceProvider, StoreOptions> optionSource
)
{
services.AddJasperFx();
// #4494: register the hosted service that drains IAsyncConfigureMarten so
// bare AddSingleton<IAsyncConfigureMarten, T>() works the same way bare
// AddSingleton<IConfigureMarten, T>() does. The helper is idempotent.
services.EnsureAsyncConfigureMartenApplicationIsRegistered();
services.AddSingleton<ISystemPart, MartenSystemPart>();
services.AddSingleton<IEventStore>(s => (IEventStore)s.GetRequiredService<IDocumentStore>());
services.AddSingleton<IDocumentStoreUsageSource>(s =>
(IDocumentStoreUsageSource)s.GetRequiredService<IDocumentStore>());
services.AddSingleton<IDocumentStoreDiagnostics>(s =>
(IDocumentStoreDiagnostics)s.GetRequiredService<IDocumentStore>());
var instrument = new SetEventStoreInstrumentation();
services.AddSingleton<IConfigureMarten>(instrument);
services.AddSingleton<IEventStoreInstrumentation>(instrument);
services.AddSingleton(s =>
{
var options = optionSource(s);
var configures = s.GetServices<IConfigureMarten>();
foreach (var configure in configures) configure.Configure(s, options);
options.ReadJasperFxOptions(s.GetService<JasperFxOptions>());
options.InitialData.AddRange(s.GetServices<IInitialData>());
// jasperfx#679 (#5258). Sweep any store-agnostic IDocumentCommitListener out of the
// container and adapt it onto Marten's own listener collection. This runs inside the
// StoreOptions factory, and session construction copies Options.Listeners strictly
// afterwards (QuerySession's constructors), so every session opened from this store
// sees them.
//
// ⚠️ PRIMARY STORE ONLY, deliberately, and it is the IInitialData line above that sets
// the precedent: a bare GetServices<T>() sweep from this factory cannot tell which store
// a registration was meant for, so applying it to ancillary stores as well would attach
// every listener in the container to every AddMartenStore<T>() in the application --
// silently, and with no way to opt one out. Ancillary stores configure through
// IConfigureMarten<T>, so their opt-in is
// services.ConfigureMarten<T>(opts => opts.AddCommitListener(listener)).
foreach (var listener in s.GetServices<JasperFx.Events.Documents.IDocumentCommitListener>())
{
options.AddCommitListener(listener);
}
options.Projections.AttachServiceProvider(s);
options.Services = s;
return options;
});
services.AddSingleton<IDocumentStore>(s =>
{
var options = s.GetRequiredService<StoreOptions>();
// for the purpose of not losing your sanity
// when running command line tools
if (JasperFxEnvironment.RunQuiet)
{
options.DisableNpgsqlLogging = true;
}
if (options.Logger().GetType() != typeof(NulloMartenLogger))
{
return new DocumentStore(options);
}
var logger = s.GetService<ILogger<IDocumentStore>>() ?? new NullLogger<IDocumentStore>();
options.Logger(new DefaultMartenLogger(logger));
options.LogFactory = s.GetService<ILoggerFactory>();
return new DocumentStore(options);
});
services.AddSingleton<IMasterTableMultiTenancy>(s => (IMasterTableMultiTenancy)s.GetRequiredService<IDocumentStore>());
// This can be overridden by the expression following
services.AddSingleton<ISessionFactory, LightweightSessionFactory>();
services.AddScoped(s => s.GetRequiredService<ISessionFactory>().QuerySession());
services.AddScoped(s => s.GetRequiredService<ISessionFactory>().OpenSession());
services.AddSingleton<IDatabaseSource>(s =>
s.GetRequiredService<IDocumentStore>().As<DocumentStore>().Tenancy);
return new MartenConfigurationExpression(services, null);
}
/// <summary>
/// Add Marten IDocumentStore, IDocumentSession, and IQuerySession service registrations
/// to your application using the configured StoreOptions
/// </summary>
/// <param name="services"></param>
/// <param name="configure"></param>
/// <returns></returns>
public static MartenConfigurationExpression AddMarten(
this IServiceCollection services,
Action<StoreOptions> configure
)
{
var options = new StoreOptions();
configure(options);
return services.AddMarten(options);
}
/// <summary>
/// Add a secondary IDocumentStore service to the container using only
/// an interface "T" that should directly inherit from IDocumentStore
/// </summary>
/// <param name="services"></param>
/// <param name="configure"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static MartenStoreExpression<T> AddMartenStore<T>(
this IServiceCollection services,
Action<StoreOptions> configure
) where T : class, IDocumentStore
{
return services.AddMartenStore<T>(s =>
{
var options = new StoreOptions();
configure(options);
return options;
});
}
/// <summary>
/// Add a secondary IDocumentStore service to the container using only
/// an interface "T" that should directly inherit from IDocumentStore
/// </summary>
/// <param name="services"></param>
/// <param name="configure"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static MartenStoreExpression<T> AddMartenStore<T>(this IServiceCollection services,
Func<IServiceProvider, StoreOptions> configure) where T : class, IDocumentStore
{
services.AddJasperFx();
services.AddSingleton<IDocumentStoreSource, DocumentStoreSource<T>>();
services.AddSingleton<ISystemPart, MartenSystemPart<T>>();
services.AddSingleton<IEventStore>(s => (IEventStore)s.GetRequiredService<T>());
services.AddSingleton<IDocumentStoreUsageSource>(s => (IDocumentStoreUsageSource)s.GetRequiredService<T>());
services.AddSingleton<IDocumentStoreDiagnostics>(s => (IDocumentStoreDiagnostics)s.GetRequiredService<T>());
var instrument = new SetEventStoreInstrumentation<T>();
services.AddSingleton<IConfigureMarten<T>>(instrument);
services.AddSingleton<IEventStoreInstrumentation>(instrument);
var stores = services
.Where(x => !x.IsKeyedService)
.Select(x => x.ImplementationInstance)
.OfType<SecondaryDocumentStores>().FirstOrDefault();
if (stores == null)
{
stores = new SecondaryDocumentStores();
services.AddSingleton(stores);
}
services.AddSingleton<IDatabaseSource>(s => s.GetRequiredService<T>().As<DocumentStore>().Tenancy);
var config = new SecondaryStoreConfig<T>(configure);
stores.Add(config);
services.AddSingleton<T>(s => config.Build(s));
services.AddSingleton<Lazy<T>>(s => new Lazy<T>(() => s.GetRequiredService<T>()));
services.AddSingleton<Func<T, IStorageOperations>>(_ => store => (IStorageOperations)store.LightweightSession());
// Default keyed session factory for the ancillary store
services.AddKeyedSingleton<ISessionFactory>(typeof(T), (sp, _) =>
{
var store = (IDocumentStore)sp.GetRequiredService<T>();
return new LightweightSessionFactory(store);
});
services.AddSingleton<IMasterTableMultiTenancy>(s => (IMasterTableMultiTenancy)s.GetRequiredService<T>());
return new MartenStoreExpression<T>(services);
}
internal static IReadOnlyList<IDocumentStore> AllDocumentStores(this IHost host)
{
return host.Services.AllDocumentStores();
}
public static IReadOnlyList<IDocumentStore> AllDocumentStores(this IServiceProvider services)
{
var list = new List<IDocumentStore>();
var store = services.GetService<IDocumentStore>();
if (store != null)
{
list.Add(store);
}
list.AddRange(services.GetServices<IDocumentStoreSource>().Select(x => x.Resolve(services)));
return list;
}
internal static void EnsureAsyncConfigureMartenApplicationIsRegistered(this IServiceCollection services)
{
if (!services.Any(
x => x.ServiceType == typeof(IHostedService) &&
x.ImplementationType == typeof(AsyncConfigureMartenApplication)))
{
services.Insert(0,
new ServiceDescriptor(typeof(IHostedService), typeof(AsyncConfigureMartenApplication),
ServiceLifetime.Singleton));
}
}
internal static void EnsureMartenActivatorIsRegistered(this IServiceCollection services)
{
if (!services.Any(
x => x.ServiceType == typeof(IHostedService) && x.ImplementationType == typeof(MartenActivator)))
{
var descriptor = services.FirstOrDefault(x =>
x.ServiceType == typeof(IHostedService) &&
x.ImplementationType == typeof(AsyncConfigureMartenApplication));
if (descriptor != null)
{
var index = services.IndexOf(descriptor);
services.Insert(index + 1,
new ServiceDescriptor(typeof(IHostedService), typeof(MartenActivator), ServiceLifetime.Singleton));
}
else
{
services.Insert(0,
new ServiceDescriptor(typeof(IHostedService), typeof(MartenActivator), ServiceLifetime.Singleton));
}
}
}
internal static void EnsureMartenActivatorIsRegistered<T>(this IServiceCollection services) where T : IDocumentStore
{
if (!services.Any(
x => x.ServiceType == typeof(IHostedService) && x.ImplementationType == typeof(MartenActivator<T>)))
{
services.Insert(0,
new ServiceDescriptor(typeof(IHostedService), typeof(MartenActivator<T>), ServiceLifetime.Singleton));
}
}
/// <summary>
/// Adds initial data sets to the separate Marten store of type "T" and ensures that they will be
/// executed upon IHost initialization
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static IServiceCollection InitializeMartenWith<T>(this IServiceCollection services,
params IInitialData[] data) where T : IDocumentStore
{
services.EnsureMartenActivatorIsRegistered<T>();
services.ConfigureMarten<T>(opts => opts.InitialData.AddRange(data));
return services;
}
/// <summary>
/// Registers type T as a singleton against IInitialData to be used in IHost activation
/// to apply changes or at least actions against the as built IDocumentStore
/// </summary>
/// <typeparam name="TData">The type that implements IInitialData</typeparam>
/// <returns></returns>
public static IServiceCollection InitializeMartenWith<TStore, TData>(this IServiceCollection services)
where TData : class, IInitialData where TStore : IDocumentStore
{
services.EnsureMartenActivatorIsRegistered<TStore>();
services.AddSingleton<TData>();
services.AddSingleton<IConfigureMarten<TStore>, AddInitialData<TStore, TData>>();
return services;
}
/// <summary>
/// Adds initial data sets to the Marten store and ensures that they will be
/// executed upon IHost initialization
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static IServiceCollection InitializeMartenWith(this IServiceCollection services, params IInitialData[] data)
{
services.EnsureMartenActivatorIsRegistered();
services.ConfigureMarten(opts => opts.InitialData.AddRange(data));
return services;
}
/// <summary>
/// Registers type T as a singleton against IInitialData to be used in IHost activation
/// to apply changes or at least actions against the as built IDocumentStore
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IServiceCollection InitializeMartenWith<T>(this IServiceCollection services)
where T : class, IInitialData
{
services.EnsureMartenActivatorIsRegistered();
services.AddSingleton<IInitialData, T>();
return services;
}
public class MartenStoreExpression<T> where T : class, IDocumentStore
{
public MartenStoreExpression(IServiceCollection services)
{
Services = services;
}
public IServiceCollection Services { get; }
/// <summary>
/// Register the Async Daemon hosted service to continuously attempt to update asynchronous event projections
/// </summary>
/// <param name="mode"></param>
/// <returns></returns>
public MartenStoreExpression<T> AddAsyncDaemon(DaemonMode mode)
{
Services.ConfigureMarten<T>(opts => opts.Projections.AsyncMode = mode);
// Only Solo/HotCold mean "this process hosts the daemon". Disabled hosts nothing, and
// ExternallyManaged (jasperfx#490) means an external system (e.g. Wolverine's managed
// event-subscription distribution) executes the async projections — Marten must not
// register its own coordination for either.
// marten#5056: guard against a repeated AddAsyncDaemon() call registering a second
// IHostedService forwarding to the same coordinator singleton. The host would call
// StopAsync twice on it at shutdown, and the second pass used to fan StopAllAsync out
// over daemons the first pass had already disposed (the marten#5055 error-log storm).
if (mode is DaemonMode.Solo or DaemonMode.HotCold && !Services.Any(x =>
x.ServiceType == typeof(Marten.Events.Daemon.Coordination.IProjectionCoordinator<T>) &&
x.ImplementationType == typeof(ProjectionCoordinator<T>)))
{
Services.AddSingleton<Marten.Events.Daemon.Coordination.IProjectionCoordinator<T>, ProjectionCoordinator<T>>();
Services.AddSingleton<IHostedService>(s => s.GetRequiredService<Marten.Events.Daemon.Coordination.IProjectionCoordinator<T>>());
}
return this;
}
/// <summary>
/// Adds a hosted service to your .Net application that will attempt to apply any detected database changes before the
/// rest of the application starts running
/// </summary>
/// <returns></returns>
public MartenStoreExpression<T> ApplyAllDatabaseChangesOnStartup()
{
Services.EnsureMartenActivatorIsRegistered<T>();
Services.ConfigureMarten<T>(opts => opts.ShouldApplyChangesOnStartup = true);
return this;
}
/// <summary>
/// Adds initial data sets to the Marten store and ensures that they will be
/// executed upon IHost initialization
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public MartenStoreExpression<T> InitializeWith(params IInitialData[] data)
{
Services.EnsureMartenActivatorIsRegistered<T>();
Services.ConfigureMarten<T>(opts => opts.InitialData.AddRange(data));
return this;
}
/// <summary>
/// Registers type T as a singleton against IInitialData to be used in IHost activation
/// to apply changes or at least actions against the as built IDocumentStore
/// </summary>
/// <typeparam name="TData">The type that implements IInitialData</typeparam>
/// <returns></returns>
public MartenStoreExpression<T> InitializeWith<TData>() where TData : class, IInitialData
{
Services.EnsureMartenActivatorIsRegistered<T>();
Services.AddSingleton<TData>();
Services.AddSingleton<IConfigureMarten<T>, AddInitialData<T, TData>>();
return this;
}
/// <summary>
/// Add a projection to this application that requires IoC services. The projection itself will
/// be created with the application's IoC container
/// </summary>
/// <param name="lifecycle">The projection lifecycle for Marten</param>
/// <param name="lifetime">
/// The IoC lifecycle for the projection instance. Note that the Transient lifetime will still be
/// treated as Scoped
/// </param>
/// <param name="configure">Optional confiuration of the projection name, version, event filtering, and async execution</param>
/// ///
/// <typeparam name="TProjection">The type of projection to add</typeparam>
/// <returns></returns>
public MartenStoreExpression<T> AddProjectionWithServices<TProjection>(ProjectionLifecycle lifecycle,
ServiceLifetime lifetime, Action<ProjectionBase>? configure = null) where TProjection : class, IMartenRegistrable
{
TProjection.Register<TProjection, T>(Services, lifecycle, lifetime, configure);
return this;
}
/// <summary>
/// Add a subscription to this Marten store that will require resolution
/// from the application's IoC container in order to function correctly
/// </summary>
/// <param name="lifetime">IoC service lifetime</param>
/// <param name="configure">Optional configuration of the subscription within Marten</param>
/// <typeparam name="T">The type of projection to add</typeparam>
/// <returns></returns>
public MartenStoreExpression<T> AddSubscriptionWithServices<TSubscription>(ServiceLifetime lifetime,
Action<ISubscriptionOptions>? configure = null) where TSubscription : class, ISubscription
{
switch (lifetime)
{
case ServiceLifetime.Singleton:
Services.AddSingleton<TSubscription>();
Services.ConfigureMarten<T>((s, opts) =>
{
var subscription = s.GetRequiredService<TSubscription>();
if (subscription is SubscriptionBase subscriptionBase)
{
configure?.Invoke(subscriptionBase);
opts.Projections.Subscribe(subscriptionBase);
}
else
{
opts.Projections.Subscribe(subscription, configure);
}
});
break;
case ServiceLifetime.Transient:
case ServiceLifetime.Scoped:
Services.AddScoped<TSubscription>();
Services.ConfigureMarten<T>((s, opts) =>
{
var subscription = new ScopedSubscriptionServiceWrapper<TSubscription>(s);
opts.Projections.Subscribe(subscription, configure);
});
break;
}
return this;
}
/// <summary>
/// Use an alternative strategy / configuration for opening IDocumentSession or IQuerySession
/// objects for this ancillary store with a custom ISessionFactory type registered as a keyed singleton
/// </summary>
/// <param name="lifetime">
/// IoC service lifetime for the session factory. Default is Singleton, but use Scoped if you need
/// to reference per-scope services
/// </param>
/// <typeparam name="TFactory">The custom session factory type</typeparam>
/// <returns></returns>
public MartenStoreExpression<T> BuildSessionsWith<TFactory>(ServiceLifetime lifetime = ServiceLifetime.Singleton)
where TFactory : class, ISessionFactory
{
var descriptor = new ServiceDescriptor(
typeof(ISessionFactory),
typeof(T),
(sp, _) =>
{
var store = sp.GetRequiredService<T>();
return ActivatorUtilities.CreateInstance<TFactory>(sp, (IDocumentStore)store);
},
lifetime);
Services.Add(descriptor);
return this;
}
/// <summary>
/// Use lightweight sessions by default for this ancillary store. Equivalent to
/// IDocumentStore.LightweightSession();
/// </summary>
/// <returns></returns>
public MartenStoreExpression<T> UseLightweightSessions()
{
return BuildSessionsWith<LightweightSessionFactory>();
}
/// <summary>
/// Use identity sessions by default for this ancillary store. Equivalent to
/// IDocumentStore.IdentitySession();
/// </summary>
/// <returns></returns>
public MartenStoreExpression<T> UseIdentitySessions()
{
return BuildSessionsWith<IdentitySessionFactory>();
}
/// <summary>
/// Use dirty-tracked sessions by default for this ancillary store. Equivalent to
/// IDocumentStore.DirtyTrackedSession();
/// </summary>
/// <returns></returns>
public MartenStoreExpression<T> UseDirtyTrackedSessions()
{
return BuildSessionsWith<DirtyTrackedSessionFactory>();
}
}
public class MartenConfigurationExpression
{
private readonly StoreOptions? _options;
internal MartenConfigurationExpression(IServiceCollection services, StoreOptions? options)
{
Services = services;
_options = options;
}
/// <summary>
/// Gets the IServiceCollection
/// </summary>
public IServiceCollection Services { get; }
/// <summary>
/// Use an alternative strategy / configuration for opening IDocumentSession or IQuerySession
/// objects in the application with a custom ISessionFactory type registered as a singleton
/// </summary>
/// <param name="lifetime">
/// IoC service lifetime for the session factory. Default is Singleton, but use Scoped if you need
/// to reference per-scope services
/// </param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public MartenConfigurationExpression BuildSessionsWith<T>(ServiceLifetime lifetime = ServiceLifetime.Singleton)
where T : class, ISessionFactory
{
Services.Add(new ServiceDescriptor(typeof(ISessionFactory), typeof(T), lifetime));
return this;
}
/// <summary>
/// Adds a hosted service to your .Net application that will attempt to apply any detected database changes before the
/// rest of the application starts running
/// </summary>
/// <returns></returns>
public MartenConfigurationExpression ApplyAllDatabaseChangesOnStartup()
{
Services.EnsureMartenActivatorIsRegistered();
Services.ConfigureMarten(opts => opts.ShouldApplyChangesOnStartup = true);
return this;
}
/// <summary>
/// Adds a hosted service to your .Net application that will assert that database matches configuration before the
/// rest of the application starts running. Prevents the application from starting if database does not match
/// configuration.
/// </summary>
/// <returns></returns>
public MartenConfigurationExpression AssertDatabaseMatchesConfigurationOnStartup()
{
Services.EnsureMartenActivatorIsRegistered();
Services.ConfigureMarten(opts => opts.ShouldAssertDatabaseMatchesConfigurationOnStartup = true);
return this;
}
/// <summary>
/// Register the Async Daemon hosted service to continuously attempt to update asynchronous event projections
/// </summary>
/// <param name="mode"></param>
/// <returns></returns>
public MartenConfigurationExpression AddAsyncDaemon(DaemonMode mode)
{
Services.ConfigureMarten(opts => opts.Projections.AsyncMode = mode);
// Only Solo/HotCold mean "this process hosts the daemon". Disabled hosts nothing, and
// ExternallyManaged (jasperfx#490) means an external system (e.g. Wolverine's managed
// event-subscription distribution) executes the async projections — Marten must not
// register its own coordination for either.
// marten#5056: guard against a repeated AddAsyncDaemon() call registering a second
// IHostedService forwarding to the same coordinator singleton. The host would call
// StopAsync twice on it at shutdown, and the second pass used to fan StopAllAsync out
// over daemons the first pass had already disposed (the marten#5055 error-log storm).
if (mode is DaemonMode.Solo or DaemonMode.HotCold && !Services.Any(x =>
x.ServiceType == typeof(Marten.Events.Daemon.Coordination.IProjectionCoordinator) &&
x.ImplementationType == typeof(ProjectionCoordinator)))
{
Services.AddSingleton<Marten.Events.Daemon.Coordination.IProjectionCoordinator, ProjectionCoordinator>();
Services.AddSingleton<IHostedService>(s => s.GetRequiredService<Marten.Events.Daemon.Coordination.IProjectionCoordinator>());
// jasperfx#430 — also resolve the JasperFx.Events base interface, so a stock host can
// GetService<JasperFx.Events.Daemon.IProjectionCoordinator>() directly instead of walking
// the registered IHostedServices for one.
Services.AddSingleton<JasperFx.Events.Daemon.IProjectionCoordinator>(s => s.GetRequiredService<Marten.Events.Daemon.Coordination.IProjectionCoordinator>());
}
return this;
}
/// <summary>
/// Use lightweight sessions by default for the injected IDocumentSession objects. Equivalent to
/// IDocumentStore.LightweightSession(); This is now the default as of Marten 9.0.3
/// </summary>
/// <returns></returns>
public MartenConfigurationExpression UseLightweightSessions()
{
return BuildSessionsWith<LightweightSessionFactory>();
}
/// <summary>
/// Use identity sessions by default for the injected IDocumentSession objects. Equivalent to
/// IDocumentStore.IdentitySession();
/// </summary>
/// <returns></returns>
public MartenConfigurationExpression UseIdentitySessions()
{
return BuildSessionsWith<IdentitySessionFactory>();
}
/// <summary>
/// Use dirty-tracked sessions by default for the injected IDocumentSession objects. Equivalent to
/// IDocumentStore.DirtyTrackedSession();
/// </summary>
/// <returns></returns>
public MartenConfigurationExpression UseDirtyTrackedSessions()
{
return BuildSessionsWith<DirtyTrackedSessionFactory>();
}
/// <summary>
/// Use configured NpgsqlDataSource from DI container
/// </summary>
/// <param name="serviceKey">NpgsqlDataSource service key as registered in DI</param>
/// <returns></returns>
public MartenConfigurationExpression UseNpgsqlDataSource(object? serviceKey = null)
{
Services.ConfigureMarten((sp, opts) =>
opts.Connection(
serviceKey != null
? sp.GetRequiredKeyedService<NpgsqlDataSource>(serviceKey)
: sp.GetRequiredService<NpgsqlDataSource>()
)
);
return this;
}
/// <summary>
/// Use configured NpgsqlDataSource from DI container
/// </summary>
/// <param name="dataSourceBuilderFactory">configuration of the data source builder</param>
/// <param name="serviceKey">NpgsqlDataSource service key as registered in DI</param>
/// <returns></returns>
public MartenConfigurationExpression UseNpgsqlDataSource(
Func<string, NpgsqlDataSourceBuilder> dataSourceBuilderFactory,
object? serviceKey = null
)
{
Services.ConfigureMarten((sp, opts) =>
opts.Connection(
dataSourceBuilderFactory,
serviceKey != null
? sp.GetRequiredKeyedService<NpgsqlDataSource>(serviceKey)
: sp.GetRequiredService<NpgsqlDataSource>()
)
);
return this;
}
/// <summary>
/// Adds initial data sets to the Marten store and ensures that they will be
/// executed upon IHost initialization
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public MartenConfigurationExpression InitializeWith(params IInitialData[] data)
{
Services.EnsureMartenActivatorIsRegistered();
Services.ConfigureMarten(opts => opts.InitialData.AddRange(data));
return this;
}
/// <summary>
/// Registers type T as a singleton against IInitialData to be used in IHost activation
/// to apply changes or at least actions against the as built IDocumentStore
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public MartenConfigurationExpression InitializeWith<T>() where T : class, IInitialData
{
Services.EnsureMartenActivatorIsRegistered();
Services.AddSingleton<IInitialData, T>();
return this;
}
/// <summary>
/// Add a projection to this application that requires IoC services. The projection itself will
/// be created with the application's IoC container
/// </summary>
/// <param name="lifecycle">The projection lifecycle for Marten</param>
/// <param name="lifetime">
/// The IoC lifecycle for the projection instance. Note that the Transient lifetime will still be
/// treated as Scoped
/// </param>
/// <typeparam name="T"></typeparam>
/// <param name="configure">Optional configuration of the projection behavior including the name, version, event filtering, and async execution behavior</param>
/// <returns></returns>
public MartenConfigurationExpression AddProjectionWithServices<T>(ProjectionLifecycle lifecycle,
ServiceLifetime lifetime, Action<ProjectionBase>? configure = null) where T : class, IMartenRegistrable
{
T.Register<T>(Services, lifecycle, lifetime, configure);
return this;
}
/// <summary>
/// Add a projection to this application that requires IoC services. The projection itself will
/// be created with the application's IoC container
/// </summary>
/// <param name="lifecycle">The projection lifecycle for Marten</param>
/// <param name="lifetime">
/// The IoC lifecycle for the projection instance. Note that the Transient lifetime will still be
/// treated as Scoped
/// </param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public MartenConfigurationExpression AddProjectionWithServices<T>(ProjectionLifecycle lifecycle,
ServiceLifetime lifetime, string projectionName) where T : class, IMartenRegistrable
{
return AddProjectionWithServices<T>(lifecycle, lifetime, x => x.Name = projectionName);
}
/// <summary>
/// Add a subscription to this Marten store that will require resolution
/// from the application's IoC container in order to function correctly
/// </summary>
/// <param name="lifetime">IoC service lifetime</param>
/// <param name="configure">Optional configuration of the subscription within Marten</param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public MartenConfigurationExpression AddSubscriptionWithServices<T>(
ServiceLifetime lifetime, Action<ISubscriptionOptions>? configure = null) where T : class, ISubscription
{
switch (lifetime)
{
case ServiceLifetime.Singleton:
Services.AddSingleton<T>();
Services.ConfigureMarten((s, opts) =>
{
var subscription = s.GetRequiredService<T>();
if (subscription is SubscriptionBase subscriptionBase)
{
configure?.Invoke(subscriptionBase);
opts.Projections.Subscribe(subscriptionBase);
}
else
{
opts.Projections.Subscribe(subscription, configure);
}
});
break;
case ServiceLifetime.Transient:
case ServiceLifetime.Scoped:
Services.AddScoped<T>();
Services.ConfigureMarten((s, opts) =>
{
var subscription = new ScopedSubscriptionServiceWrapper<T>(s);
opts.Projections.Subscribe(subscription, configure);
});
break;
}
return this;
}
}
internal class AddInitialData<T, TData>: IConfigureMarten<T> where T : IDocumentStore where TData : IInitialData
{
private readonly TData _data;
public AddInitialData(TData data)
{
_data = data;
}
public void Configure(IServiceProvider services, StoreOptions options)
{
options.InitialData.Add(_data);
}
}