CDI Keeps all Injected tree references of SessionScoped beans? - dependency-injection

I am starting a new project with JavaEE 7 and declared a Sessionscoped bean to maintain the web logged user information in session.
The UserSessionBean, as I named it, is intended to be lightweight - trying to avoid lots of data to be kept in the session by Weld. But in some cases I need to get all user information, so added a getUser() method which must query and retrieve a UserEntity from JPA. In order for the method to do its job, I need to #Inject other resources onto the UserSessionBean.
My question is: These dependant resources will be kept and serialised within the UserSessionBean by Weld until the context is destroyed?
The weld documentation says this:
An instance of a dependent bean is never shared between different
clients or different injection points. It is strictly a dependent
object of some other object. It is instantiated when the object it
belongs to is created, and destroyed when the object it belongs to is
destroyed.
That makes me think the all SessionBean tree is kept by weld during session life, but how can I keep a lightweight SessionBean and use injected CDI resources on it?

Since what you're injecting are also CDI beans, it is not the beans themselves that get serialised, but their lightweight proxies. Upon deserialisation, the proxies dynamically resolve the correct beans for whatever scope they are. See section 5.4 Client Proxies of the CDI1.0 spec. Hence, your bean is as lightweight as possible.

Related

Getting a scoped component from a IDocumentStoreListener

I have an ASP.NET 5 app using RavenDB, and I'm trying to create an attribute that will create a "Changeset" document with the keys of all the documents that were stored by the action.
For that purpose, I created an ActionFilterAttribute instantiated via ServiceFilterAttribute, which is registered as Scoped, that sets a flag on another Scoped component, let's call it ChangesetAccessor, which holds the list of changes.
The IDocumentStore is obviously a Singleton, and the listener (IDocumentStoreListener implementation) is manually instantiated. It needs access to the current ChangesetAccessor, so I thought giving it a reference to the IServiceProvider so it can call GetService<ChangesetAccessor> as needed would be enough, but it is receiving a different instance.
How can I get the ChangesetAccessor for the "current request" from my listener?
You can actually access RequestServices off of the HttpContext to get scoped instances. It's kind of backwards, and really will depend on Microsoft.AspNet to do it, but it will work for your situation; interestingly, IHttpContextAccessor is a singleton, too, though it gives you a scoped value.
// injected:
IHttpContextAccessor httpContextAccessor;
// in your method:
httpContextAccessor.HttpContext.RequestServices.GetService<ChangesetAccessor>()

Why use a ShoppingCart as a Stateful Sesson Bean?

One typical example of using a Stateful Session Bean is through a ShoppingCart example. We create a bean instance of the ShoppingCart class, then store this instance within a HttpSession.
However, the same can be achieved easily with the ShoppingCart class being a normal Java class (or a stateless session bean). A request of adding a product comes in, we create a cart object, then put that cart object inside a HttpSession.
So, I don't see the point of using a stateful session bean ShoppingCart here. And in general, a stateful session bean doesn't seem to play any significant roles.
I would rephrase your question:
Why should I use mechanism for automatic session based bean management (maintaining one instance per session, persisting inside session) if I can implement it myself?
Yes, you can implement it yourself and it would be pretty simple. However you can just use Java EE mechanisms for that.

Inject with different scope when using DbContext with custom resource provider

In an application I have the following components (among others):
MyDbContext : Entity framework data access
DBResourceProviderFactory : A custom ResourceProviderFactory providing a custom IResourceProvider (called DBResourceProvider...)
Other services
StructureMap
The custom resource provider is looking resources up in the db using MyDbContext, injected similarly as described in this SO answer.
The MyDbContext is also used in various other services, and since it is a web application, I use StructureMaps HttpContextScoped method to limit the lifetime of MyDbContext to the lifetime of the request (see an other SO question and its answer on this subject):
x.For<MyDbContext>().HttpContextScoped();
However, it seems that the lifetime of an IResourceProvider is not limited to a single http request. Therefore, DBResourceProvider keeps hanging onto a MyDbContext reference which will be disposed after the first request.
How can I handle this lifetime mismatch - have StructureMap return a transient MyDbContext for IDbResourceProvider while returning HttpContext-scoped instances to all other services?
Do I need two different implementations to do that? A marker interface?
Or is it a bad idea to use Entity Framework to look up localized resources in the first place (performance etc.)?
If you have a service that has (or needs to have) a long lifetime than (one of) its dependencies, the general solution is to use a factory to get those dependencies.
In your situation the solution might be simple. When your DBResourceProvider is defined in your composition root of your MVC application, it would simply succeed to use the DependencyResolver.Current.GetService method to get the MyDbContext.
When the DBResourceProvider service isn't part of the composition root (for instance because it contains business logic that you need to test), you could either extract that logic into its own class, to allow the service to be in the composition root, or you can inject a (singleton) factory (for instance IDbContextFactory or Func<MyDbContext>) that allows you to get the proper instance to be resolved.

What happens to #SessionScoped #ManagedBean which is already in HttpSession?

Old code creates a #SessionScoped #ManagedBean (namely UserSession) at the first request in a ServletFilter and puts it in the HttpSession (if not already there).
Now what happens when some EL expression tries to access that ManagedBean the first time? I expected a second instance of UserSession (one created manually and one from JSF). So I instrumented the constructor, #PostConstruct and #PreDestroy with a few logging statements. Now it seems JSF never creates the UserSession - only the constructor is called.
Is this possible? Can JSF reuse that bean from HttpSession? Is it legit to put #SessionScoped beans in HttpSession?
Your observation is correct. Under JSF's covers, JSF itself also stores session scoped managed beans as an attribute of the HttpSession. So if it's already present, it will just be reused, regardless of the way how it has ended up in there.
Whether that's good or bad depends on the concrete functional requirement. Given your astonishment, I'd guess that it's bad and that you need to revise either the approach or the functional requirement. Perhaps you need a secondary (session scoped?) managed bean which injects the particular session attribute by #ManagedProperty.

IoC Dependency Injection for stateful objects (not global)

I'm new to this IoC and DI business- I feel like I get the concept if you are passing along objects that are of a global scope, but I don't get how it works when you need to pass around an object that is of a specific logical state. So, for instance, if I wanted to inject a person object into a write file command object- how would I be able to choose the correct person object dynamically? From what I have seen, I could default construct the object, but my disconnect is that you wouldn't use a default person object, it would need to be dynamic. I assume that the IoC container may just maintain the state of the object for you as it gets passed around, but then that assuems you are dealing in only one person object because there would be no thread safety, right? I know I am missing something, (maybe something like a factoryclass), but I need a little more information about how that would work.
Well, you can always inject an Abstract Factory into your consumer and use it to create the locally scoped objects.
This is sometimes necessary. See these examples:
MVC, DI (dependency injection) and creating Model instance from Controller
Is there a pattern for initializing objects created via a DI container
Can't combine Factory / DI
However, in general we tend to not use DI for Entities, but mostly for Services. Instead, Entities are usually created through some sort of Repository.
When you construct an service object (e.g. WriteFileService), you inject into it things it needs internally to complete it's job. Perhaps it needs a filesystem object or something.
The Person object in your example should be passed to the service object as a parameter to a method call. e.g. writeFileService.write(person)

Resources