Explicitly pass context object versus injecting with IoC

Posted by SonOfPirate on Programmers See other posts from Programmers or by SonOfPirate
Published on 2012-12-12T01:17:41Z Indexed on 2012/12/12 5:16 UTC
Read the original article Hit count: 258

I have a layered service application where the service layer delegates operations into the domain layer for execution. Many of these operations need to know the context under which they are operation. (The context included the identity of the current user, culture information, etc. received from the caller.)

For example, I have an API method that returns a list of announcements. The list is based on the current user's role and each announcement is localized to their culture. The API is a thin-facade that delegates to an Application Service in my domain layer. The Application Service method obviously needs to know the context of the current request/operation as another call to the same API from another user should result in a different list. Within this method, we also have logging that uses some of the context information so we a clear understanding of the context when the operation was performed (this is especially useful if something goes wrong.)

While this is a contrived example, in the real world, my Application Services will coordinate operations with many collaborative components, any number of them also needing the context information.

My choice is to pass the context to the Application Service which would then pass it with any calls to collaborators or have the IoC container satisfy the dependency the Application Service and any collaborators have on the context.

I am wondering if it is considered good/bad, best practices/code smell, etc. if I pass the context object as a parameter to the domain methods or if injecting the context via an IoC container is preferred.

(EDIT: I should mention that the context object is instantiated per-request.)

© Programmers or respective owner

Related posts about dependency-injection

Related posts about domain-driven-design