You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Make using scoped services in notification handlers less painful. (#11733)
* Add failing test to demo issue with handlers + scoped dependencies.
* Make using scoped services in notification handlers less painful.
* Update comments for accuracy.
/// Background - During v9 build we wanted an in-process message bus to facilitate removal of the old static event handlers. <br/>
92
+
/// Instead of taking a dependency on MediatR we (the community) implemented our own using MediatR as inspiration.
93
+
/// </para>
94
+
///
95
+
/// <para>
96
+
/// Some things worth knowing about MediatR.
97
+
/// <list type="number">
98
+
/// <item>All handlers are by default registered with transient lifetime, but can easily depend on services with state.</item>
99
+
/// <item>Both the Mediatr instance and its handler resolver are registered transient and as such it is always possible to depend on scoped services in a handler.</item>
100
+
/// </list>
101
+
/// </para>
102
+
///
103
+
/// <para>
104
+
/// Our EventAggregator started out registered with a transient lifetime but later (before initial release) the registration was changed to singleton, presumably
105
+
/// because there are a lot of singleton services in Umbraco which like to publish notifications and it's a pain to use scoped services from a singleton.
106
+
/// <br/>
107
+
/// The problem with a singleton EventAggregator is it forces handlers to create a service scope and service locate any scoped services
108
+
/// they wish to make use of e.g. a unit of work (think entity framework DBContext).
109
+
/// </para>
110
+
///
111
+
/// <para>
112
+
/// Moving forwards it probably makes more sense to register EventAggregator transient but doing so now would mean an awful lot of service location to avoid breaking changes.
113
+
/// <br/>
114
+
/// For now we can do the next best thing which is to create a scope for each published notification, thus enabling the transient handlers to take a dependency on a scoped service.
115
+
/// </para>
116
+
///
117
+
/// <para>
118
+
/// Did discuss using HttpContextAccessor/IScopedServiceProvider to enable sharing of scopes when publisher has http context,
119
+
/// but decided against because it's inconsistent with what happens in background threads and will just cause confusion.
0 commit comments