Let's say I have a blog, I use DDD approach, I need to pass an instance of PaginationParameters
class to PostsRepository
, is it ok to bind DI container to concrete instance of PaginationParameters with exact values (let's say page_number=1, page_size=10) passed from HTTP request?
-
This question seems to assume that DI registration occurs for each incoming HTTP request individually. Generally speaking, this is not the case; but this requires more information on exactly what web server technology you're using (and if relevant, how you've configured the DI container to be constructed).Flater– Flater2023年10月03日 22:39:46 +00:00Commented Oct 3, 2023 at 22:39
-
@Flater yes exactly: I want to do some DI at the start, and then another DI for each incoming request. Is this sound?cool_cat– cool_cat2023年10月04日 15:40:11 +00:00Commented Oct 4, 2023 at 15:40
-
You may be confusing DI configuration with the factory pattern. It's a common misconception because a DI container is a kind of factory (a really, really smart one), but DI containers do not usurp your everyday factory pattern needs. To add to the confusion, that factory would then probably still be registered in the DI container, so it's important that you understand the reason why this is better contained in an explicit factory and not a DI container.Flater– Flater2023年10月06日 00:11:31 +00:00Commented Oct 6, 2023 at 0:11
1 Answer 1
Pagination information is usually passed as part of the request. Configuring this information in the DI container implies it is potentially shared state in the application, when in fact the usual use case requires this to be transient.
That being said, there is nothing wrong with configuring your DI container to use a concrete type. The issue here is the expected lifetime of the object. Request parameters are not typically initialized when the application starts up, or blindly initialized when an HTTP request begins to be processed. Instead, consider method injection.
Method injection is a form of dependency injection where you pass parameters to a method. Yup. Good 'ol fashioned "pass stuff to a method".
The repository method should accept a PaginationParameters
object where applicable. The controller or framework should initialize the PaginationParameters
object from the HTTP request. If this information is missing from the request, the controller is free to initialize a sensible default.
Explore related questions
See similar questions with these tags.