Contexts - BisocM/CQRSharp GitHub Wiki
All requests within the CQRSharp framework have a context attached to them by the Dispatcher. This context is mandatory, and will be created no matter what. The consuming user has the option to cusomize the type of the context, the creation pipeline and the data transferred within the context.
All contexts are created via any concrete implementation of the IRequestContextFactory
. Upon request execution, the dispatcher identifies the correct type of the context that is used for that specific request instance, and uses the relevant concrete implementation of IRequestContextFactory
to generate the context, according to the define logic.
Below is the default implementation:
using CQRSharp.Shared.Core.Data.Interfaces.Context;
using CQRSharp.Shared.Core.Data.Interfaces.Markers.Request;
namespace CQRSharp.Core.Factories;
/// <summary>
/// Provides a default implementation of the <see cref="IRequestContextFactory" /> interface.
/// Used to create instances of <see cref="RequestContextBase" /> with default values for request and user IDs
/// when no custom factories are registered.
/// </summary>
public class DefaultRequestContextFactory : IRequestContextFactory
{
/// <inheritdoc />
public RequestContextBase CreateContext(IRequest request)
{
//Return a default instance of RequestContextBase
return new RequestContextBase();
}
}
In order to have a request context factory with a custom input, you must register it within the DI container, using IRequestContextFactory<> as the base:
In the future, the
DependencyInjectionExtensions
class provided by the library might have a custom override for this, for ease of usability. Please be aware of this if this section is not updated.
services.AddSingleton<IRequestContextFactory<CustomContext>, CustomContextFactory>();
with the CustomContextFactory
being:
public class CustomContextFactory : IRequestContextFactory<CustomContext> { }
This way, you are allowed to define logic for each specific context type that is present and may be used within your application, as you can define as many custom context factories as you need, and the Dispatcher would map to the correct one automatically.
Currently, all request types do support direct data transfer within the class itself. However, in asynchronous applications, it is not quite recommended. It is far more optimal to create transient contexts that are carried by requests, with components incorporated within them, alongside lazy loading for bigger requests, or requests that are particularly heavy.