While there is no stock infrastructure for this, I did the following:
I put the ObjectGraph
into the ServletContext
of the web server. Then, for each Servlet, I can do the following,
@Inject
SomeDependency dependency;
@Inject
SomeOtherDependency otherDependency;
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
((ObjectGraph) filterConfig.getServletContext().getAttribute(DaggerConstants.DAGGER_OBJECT_GRAPH)).inject(this);
}
where I have previously defined the DaggerConstants
myself.
There are likely a variety of ways to get the ObjectGraph
into the ServletContext
, depending on what your application is. We use an embedded jetty server, so we control everything during startup. Not sure how you would do it in a general container, but presuming you instantiate your main ObjecGraph
through some init servlet, you would do it there.
servletContext.setAttribute(DaggerConstants.DAGGER_OBJECT_GRAPH, objectGraph);
Note that our application uses a single ObjectGraph for the entire application, which might not be your situation.