Tuesday, July 28, 2009

You don't need session in Grails service

From time to time there are questions or blog posts that explain how to obtain access to web session from the grails service or domain class. If you really need to access session from the service class e.g. this post from Robert can help you.

But before you start reusing session in your services or even domain classes be careful and think if you really want that. Service should be more or less simple Java class and when ever possible should not depend on special environment classes. And session is actually very special web application environment class.

So what to do if in the service you really need that value from the session? Well the answer is of course very simple. Send it as a method parameter. Or another way is Robert's approach to create service that will return that value from session and inject it into service that really needs that value.

This way your services will not depend on the web container context and you can easily port them to other environment.

No comments: