Closed Abdulrahman-Tayara closed 1 year ago
@Abdulrahman-Tayara Thanks for your contribution, Could you give me a simple example of usage of this feature, and what is its advantage comparing to existing functionality for registering handlers?
@mehdihadeli The major advantage is avoiding the instance creation at the compiling time and make it at the runtime (on demand), so you don't have to create an instance for each handler and its dependencies at the application startup. Also by using the factory, the handler will be created for each request/event instead of the singleton instance, this will prevent any shared resources between the handler instances.
Here is an example of using the factory:
// ProductByIdQueryHandlerFactory new instance for each Send/Publish
func ProductByIdQueryHandlerFactory() mediatr.RequestHandler[*queries.GetProductByIdQuery, *gettingProductByIdDtos.GetProductByIdQueryResponse] {
productRepository := repository.NewInMemoryProductRepository()
getByIdQueryHandler := queries.NewGetProductByIdHandler(productRepository)
return getByIdQueryHandler
}
// ProductByIdQueryHandlerFactorySingleton same instance for each Send/Publish
func ProductByIdQueryHandlerFactorySingleton() mediatr.RequestHandlerFactory[*queries.GetProductByIdQuery, *gettingProductByIdDtos.GetProductByIdQueryResponse] {
var instance mediatr.RequestHandler[*queries.GetProductByIdQuery, *gettingProductByIdDtos.GetProductByIdQueryResponse]
return func() mediatr.RequestHandler[*queries.GetProductByIdQuery, *gettingProductByIdDtos.GetProductByIdQueryResponse] {
if instance == nil {
productRepository := repository.NewInMemoryProductRepository()
getByIdQueryHandler := queries.NewGetProductByIdHandler(productRepository)
instance = getByIdQueryHandler
}
return instance
}
}
// Registration
err1 := mediatr.RegisterRequestHandlerFactory(ProductByIdQueryHandlerFactory)
err2 := mediatr.RegisterRequestHandlerFactory(ProductByIdQueryHandlerFactorySingleton())
Add ability to register a factory for the request/event handler instead of the direct value.