EJB3 Caching Instance Variables - variables

I've noticed some strange code on a project I am working on - its a SLSB EJB3, and it uses a private instance variable to maintain a cache of data (it even calls it dataCache or something), with a getter/setter. For EJB2 and bellow, this was a typical EJB antipattern - SLSBs are not meant to retain state in between invocations, theres no guarantee you'll see the same data on a subsequent invocation. One of my colleagues said maybe its ok in EJB3 (we don't have much EJB3 experience), but still, its a Stateless Session Bean - why is it trying to maintain state, this doesn't make sense.
Can anyone confirm if this is still a bad idea in EJB3 land, or if somehow it is ok?
Thanks if you can help, Justin

In EJB 3.1 you'd do this cleanly by having a separate singleton bean (with the #Singleton annotation) and injecting via #EJB it into the session beans that need it.
Before EJB 3.1, there is no really clean way and you have to use some sort of hack.

For EJB2 and bellow, this was a typical EJB antipattern - SLSBs are not meant to retain state in between invocations, there's no guarantee you'll see the same data on a subsequent invocation.
This is true and this is somehow a smell (because often wrongly used: people tend to forget that there is no guarantee to get the same instance, that the container could remove some bean from the pool to free resources, that beans could be distributed across JVMs, etc).
One of my colleagues said maybe its OK in EJB3 (we don't have much EJB3 experience), but still, its a Stateless Session Bean - why is it trying to maintain state, this doesn't make sense.
What was true with Stateless Session Beans (SLSB) in EJB 2.x is still true with EJB 3.0, SLSB are still SLSB, EJB 3.0 didn't redefine statelessness.
But if you use an instance variable to hold some read-only resource that is expensive to load (and make sure to load it if null), it should be ok.
Related questions
Stateless and Stateful Enterprise Java Beans
Stateless session bean with instance variables
Static vs Instance members in Stateless EJBs
Why stateless session beans are single threaded?

Related

Is keeping all logic in local EJBs is good?

I have some business logic in stateless EJB, but the logic is too complex and too big for one EJB. So I can see the following things to do here:
1) Extract the logic into some helper classes and instantiate them in EJB, so EJB will be like a facade for all the business logic.
Disadvantages that will be here: EJB has a lot of injected resources (e.g. queues, connectionFactory, other EJB's), so I have to pass those in a constructor to helper classes. Maybe not that convenient, but doable.
2). Create more local stateless EJBs with business logic and inject.
Disadvantages that will be here: I'm not sure if having a lot of local EJB's actually affects the performance of the whole application. Probably somehow it does: it has to add it to pool, instantiate etc.
I'm using EJB3.0 and WebLogic as a container.
What would u say will be a better approach?
Thanks

Can Castle Windsor be used to implement IDependencyResolver in ASP.NET MVC 4?

I read this article and saw many people commented that do not use Castle Windsor to implement IDependencyResolver in ASP.NET MVC3 and stick with a custom IControllerFactory. Basically my questions now are:
Do not use Castle Windsor to implement IDependencyResolver. Is this still true in ASP.NET MVC 4 ?
If 1 is the case. Can any other DI container (Unity, StructureMap) has the same problem as Castle Windsor? Can I use any alternative?
Thanks a lot
EDIT
Sounds to me that Castle Windsor should NOT be used to implement IDependencyResolver. I have decided to use some other DI container, such as StructureMap
There is no difference between MVC3 and MVC4 in regards to IDependencyResolver, other than the fact there is a separate resolver for WebAPI.
In my opinion, Mike Hadlow is a bit too caustic on this subject, and many other people have jumped on the bandwagon without truly considering why.
Yes, it's true that Castle Windsor has a specific object lifestyle (ie lifetime management object) called Pooled that often requires you to call Release on it. And when using this lifestyle, you should probably not use IDependencyResolver because it does not provide access to this Release method (although there are ways around that too).
However, I feel it's generally bad to use this lifestyle in a web application, and you should instead use the PerWebRequest lifestyle, which will automatically release objects at the end of the web request. If this is what you are using, then there is no problem with using IDependencyResolver with Castle Windsor.
Why do I think Hadlow is too caustic? Well, because he bases his entire argument on this:
"That’s right, no ‘Release’ method. You can provide a service from your IoC container, but there’s no way to clean it up. If I was going to use this in Suteki Shop, I would have a memory leak of epic proportions."
He then goes on to reference Krzysztof Koźmic's article regarding lifestyle management, but neglects to reference his followup article which I will do here:
http://kozmic.net/2010/08/27/must-i-release-everything-when-using-windsor/
Note what he says here:
"Since as I men­tioned in my pre­vi­ous post, Wind­sor will track your com­po­nent, it’s a com­mon mis­con­cep­tion held by users that in order to prop­erly release all com­po­nents they must call Release method on the container."
He goes on to talk about various other aspects as well, but in general, I don't think most people will be using Pooled or Transient objects that required disposal in a web application. And if you do, then you should know not to use IDependencyResolver then. Otherwise, you should have no problems.
I know I will probably get a lot of grief from people arguing otherwise, but I simply do not see this as the end of the world issue that people like Hadlow seem to think it is, since there are so many alternatives, and workarounds even when you do need to call Release.
Besides all this, using a lifestyle that requires calling Release means extra work for you, the developer. You now have to manage the object lifetimes and remember to dispose of objects, and failing to do so creates memory leaks. This is, essentially, nullifying the benefits of garbage collection in my opinion. I only ever use transient objects with things that do not need disposal, and I never use pooled objects.
By the way, I may be wrong, but I don't think any other container has this problem. This leads me to the conclusion that it's Windsor that is broken, rather than MVC, when every other container out there seems to not have an issue with this. Windsor likes to stubbornly hang on to its version of reality though, so YMMV.
The advice not to use IDependencyResolver is silly, because it can be used with Castle Windsor, even though the interface lacks a release method. The solution is simply to let the IDependencyResolver implementation cache each requested instance (in a cache bounded to the web request, using HttpContext.Items for instance). At the end of the web request all cached instances (usually just a few) can be released.
To be able to release all instances at the end of the web request, you should either register an Request_Ends event in the global.asax or register a HttpModule that does this.
You can call this a workaround, but not using the IDependencyResolver is not really an option, since it is too deeply integrated with MVC. Besides, other containers (such as Ninject and Simple Injector) use this same approach (using an HttpModule) to 'release' instances.
It's unfortunate though, that there isn't an official NuGet packages for omtegrating Windsor with MVC, since now you'll have to implement this yourself. All other frameworks do have such package btw. But again, it isn't that hard to implement this yourself.
Other IoC containers already show that it is possible to implement release as an implementation detail and you don't need Release as part of the IDependencyResolver contract. The MVC designers actually did the right thing by removing such method from the API.
While I agree implementing IDependencyResolver is possible and not terribly difficult.. and yes, depending on the lifestyles at play, explicitly Release()'ing may not matter... and yes, there are ways to force a Release() by caching the instance somewhere as well as other subtle tricks - I think this is alot to leave to interpretation and can be problematic and hard to track down. Understanding when Windsor is going to track an instance isn't always immediately obvious (i.e. if the component has decommission concerns vs. not, lifestyle, etc.). One of the core value-add's of IoC is to centralize the responsibility of object creation and instance management. To properly do that and have separation of concerns - you need to have an architecture that you can trust will serve you well in call scenarios and that IMO means having a iron clad answer for Release()'ing instance of all flavors. My advice is to always implement a design that will allow Release to be called - especially on roots (i.e. a Controller).
The final argument against IDependencyResolver is you have to register a number of MVC system components if you integrate at this level. That's too intimate of a dance between my app and the framework beneath it for my taste. IControllerFactory gives a much more targeted integration point, you don't have to register MVC system components and you get a Release() hook. So, unless you want to override MVC System components, I see very little reason to implement IDepedencyResolver over IControllerFactory. I see the opposite argument in fact. I personally wised up to this on this thread over here which shows both approaches.
Hope this helps

Antipatterns of IoC container usage. Why IoC containers are so complex and used so "fancy" way?

I'm seriously start thinking that usage of IoC container provokes to create overdesigned solutions (at least it provokes me to try to use various unnecessary features:).
It's the time to synchronize my "IoC" antipatterns list with community one's..
My short experience tell that it is absolutely enough to call Resolve method once per application at startup to resolve some infrastructure singletons and initiate with them "transient object's factory" that could produce new "smaller life time grain factories" . Even to make those factories thread safe (e.g. create one instance per thread) is so easy to achieve by adding 10 code lines into factory... Still those factories are much more simpler then "library's integration with IoC tool". Interception? Just create your own wrappers... Life time managers / dependency strategies/ parent containers? Call the Resolve only once at bootstrapper and you won't think about that.
Could you help me to understand why developers call Resolve several times on different application layers (by passing container or by passing delegate to container) and then have a lot of things to think about? I really worry that I miss something.
Some kind of IoC are anti-patterns or may be in some cases. For example the service locator antipattern. But if you are using constructor injection at the beginning of your application - and only there - then it should not lead to an anti-pattern.
Injecting a DI container interface in a class is a wrong use of constructor injection. If DI is not part of the business logic of your class it should not know or depend on DI container nor should it depend on IKitchen. It's only fine to inject your DI container in some kind of helper or service working in conjunction with your dependency injection container, because it's purpose is to work with or around DI container. The examples in the links you give are misuse of IoC. It does not mean that IoC in general is an anti-pattern.
I think the correct question would be "Can constructor injection be an anti-pattern?". So far I've never faced any situation or seen any example where it was so I would say "no", until I face such a situation.
When it was not clear to me how to use an IoC container, I decided to stop using it, because I thought was just an overcomplication over the simple dependency injection.
It is true though that even without IoC is possible to fall in the over-injection cases.
A while ago I read some posts from the author of ninject that opened my mind.
As you already know the injector should be used only inside the context root. However, in order to avoid over-injections, I decided to introduce an exception of the rule for injected factories.
In my framework, factories (and only factories) can use the injector container. Factories are binded in the container in the context root and therefore can be injected. Factories become valid dependencies and are used to create new objects inside other objects, using the injector container to facilitate dependencies injection.
Read This
Clearly something wrong. New library should not bring additional complex code.
I've found somebody who possibly could understand me :)
Constructor over-injection anti-pattern
Other antipattern in my eyes is pushing the initialization of container "deeper" then actual bootsrapper.
For example Unity and WCF recommendations
Bootstrapper in wcf app is the service constructor, then just put container initialization to constructor. I do not understand reasons to recommend to go for programming wcf sevice behaiviors and custome sevice host factory: if you want to have "IoC container free" bootstrapper - it is absurd, if you need to have "IoC container free" service contract implementation - just create second "IoC container free" service contract implementation.

Is Kernel.Get<T>() threadsafe + good pattern to share the kernel among components

Is Kernel.Get() threadsafe? My goal is share an instance of my kernel among all my componenets and they may all very well call Kernel.Get() at the same time on different threads.
Is Kernel.Get() thread safe?
What is the best pattern to share the application kernel among all application components which are sitting in different dll's? I prefer not to pass an instance of a factory to every component of my application if this makes sense.
Get is threadsafe but creating new kernel instances (ctor) is currently not threadsafe.
Generally you should try to minimize your access to the kernel to an absolute minimum. Accessing the kernel form everywhere is a very bad design and makes your code much less reusable. See Service Locator Antipattern
The only situations where you access the kernel should be:
Once in the composite root of the application (e.g. Program.Main, App.xaml, MVC Controller creation)
Inside a factory if you don't know how many instances you need when the composite root is created
Inside a factory if you don't know which implementation is required when the composite root is created
Inside a factory if you need to create a component late due to memory/resource constraints.
In all cases limit the access to the kernel to the composite root and inject factories (class or Func<T>) to the classes where you need to create objects during runtime. The best way to give those factories access to the kernel is still constructor injection even if you do not prefer doing so. Or use Func<T> ( Does Ninject support Func (auto generated factory)? ).
Yes, it is thread safe; The primary app I work on has a single kernel that serves a large SAAS app. So it gets pounded and it does just fine. We also have a multi-threaded page generator test suite that exposed a thread issue in Ninject last fall, but has been fixed and has been fine since then. So I know for sure that it's ok.
There are lots of different patterns for exposing the kernel. We use a ServiceLocator pattern (basically a static container for the container.)
For the different dll's. We have a NinjectModule in each dll that does it's own bindings and then the app does a assembly scan for NinjectModules at startup when it sets of the ServiceLocator.

Implementing repositories using NHibernate and Spring.Net

I'm trying to get to grips with NHibernate, Fluent NHibernate and Spring.
Following domain-driven design principals, I'm writing a standard tiered web application composed of:
a presentation tier (ASP.Net)
a business tier, comprising:
an application tier (basically a set of methods made visible to UI tier)
repository interfaces and domain components (used by the application tier)
A persistence tier (basically the implementation of the repository interfaces defined in the business tier)
I would like help determining a way of instantiating an NHibernate ISession in such a way that it can be shared by multiple repositories over the lifetime of a single request to the business tier. Specifically, I would like to:
allow the ISession instance and any transaction to be controlled outwith the repository implementation (perhaps by some aspect of the IOC framework, an interceptor?)
allow the ISession instance to be available to the repositories in a test-friendly manner (perhaps via injection or trough some shared 'context' abstraction)
avoid any unnecessary transactions being created (i.e. when only read-only operations have been executed)
allow me to write tests that use SQLLite
allow me to use Fluent NHibernate
allow the repository implementation to remain ignorant of the host environment. I don't yet know if the businese tier will run in-process with the presentation tier or will be hosted separately under WCF (in IIS), so I don't want to bind my code too closely to a HTTP context (for example).
My first attempt to solve this problem had been using the Registry pattern; storing the ISession instance in a ThreadStatic property. However, subsequent reading has suggested that isn't the best solution (as ASP.Net can switch the thread within the page lifecycle, I believe).
Any thoughts, part solutions, pattern names, pointers to up-to-date samples (NHibernate 2) will be most gratefully received.
I have not used Spring.NET so I can't comment on that. However, the rest sounds remarkably (or perhaps not so remarkably; we're hardly the first to implement these things ;) similar to my own experience. I too had trouble finding a One True Best Practice so I just read as much as I could and came up with my own interpretation.
In my situation I wanted transaction/session management to be external to the repository as well as keep repository concerns from bubbling up out of them (i.e. the code using the repository should not need to know that it's using NHibernate internally and shouldn't need to know anything about NHibernate session management). In my case it was decided that transactions would be created by default lest developers forget them, so I had to have a read-only escape mechanism. I went with the Unit of Work pattern with the NHibernate ISession instance store inside. Calling code (I also created a DSL interface for the UoW) might look something like:
using (var uow = UoW.Start().ReadOnly().WithHttpContext()
.InNewScope().WithScopeContext(ScopeContextProvider.For<CRMModel>())
{
// Repository access
}
In practice, that could be as short as UoW.Start() depending on how much context is already available. The HttpContext part refers to the storage location for the UoW which is, unsurprisingly, the HttpContext in this case. As you mentioned, for a ASP .NET application, HttpContext is the safest place to store things. ScopeContextProvider basically makes sure the right data context is provided for the UoW (ISession instance to the appropriate database/server, other settings). The "ScopeContext" concept also makes it easy to insert a "test" scope context.
Going this route makes the repositories explicitly dependent on the UoW interface. Actually, you might be able to abstract it some but I'm not sure I see the benefit. What I mean is, each repository method retrieves the current UoW instance and then pulls out the ISession object (or simply a SqlConnection for those methods that don't use NHibernate) to run the NHibernate query/operation. This works for me though because it also seems like the ideal time to make sure that the current UoW is not read-only for methods that might need to run CRUD.
Overall, I think this is one approach that solves all your points:
Allows session management to be external to the repository
ISession context can be mocked or pointed at a context provider for a test environment
Avoids unnecessary transactions (well, you'd have to invert what I did and have a .Transactional() call or something)
I can't see why you couldn't test with SQLite since that's more of an NHibernate concern
I use Fluent NHibernate myself
Allows the repository to be ignorant of the host environment (that is, the repository caller controls the UoW storage context)
As for the UoW implementation, I'm partially kicking myself for not looking around more before I started. There's a project called machine.uow which I understand is fairly popular and works well with NHibernate. I haven't played with it much so I can't say if it solves all my requirements as neatly as the one I wrote myself, but it might have saved development time as well.
Perhaps we'll get some comments as to where I went wrong or how to improve things, but I hope this is at least helpful in some way.
For reference, the software stack I'm using is:
ASP.NET MVC
Fluent NHibernate on top of NHibernate
Ninject for dependency injection
What you are describing is supported by the Spring.NET framework almost out of the box. Only for FluentNHibernate you need to add a custom SessionFactory (not a lot of code, look here:Using Fluent NHibernate in Spring.NET) to Spring.NET.
Every repository can use the same ISession, just inject the SessionFactory in your repositories and use Spring.NET's transaction services.
Just try it out, they have pretty thorough documentation imho.