Single instance of an object per transaction - spring

I have a use case, that theoretically seems to me as it would be a solved problem. But i'm not able to find a sure fired implementation.
I've created a RESTful API, using Apache CXF, Spring and Hibernate
This application encompasses a standard Service-Proxy-DAO layered structure
I need to instantiate a custom logger object at my service (or pre-service) layer and initialize a bunch of parameters which will remain constant, for the most part through every call that goes through my application layers and back.
How can i, for every individual service call, initialize this logger object once, and use it across all my layers without having to instantiate it everytime. Either i inject the initialized object in every class i need or something on those lines.
I don't want to use static blocks, or pass the object in method signatures.
Is there anything that i can use as a part of the Spring, CXF or other java framework that allows me to implement this use-case.
EDIT: I would define a transaction as a single call to a web service endpoint, from invocation to response.

ThreadLocal would be an ideal candidate to solve your problem.
UPDATE:
Creating a thread local that is available in all the places where this "shared" reference is required will give all these contexts access to this resource without having to pass the reference around.
see http://www.appneta.com/blog/introduction-to-javas-threadlocal-storage/ - looks like a good explanation of how to use thread local and also deals with your problem space.

Related

Why do we need the Abstract Factory pattern?

I am reading the chapter 11 page number 90 of clean architecture.
I agree with author that we should use interfaces instead of depending upon the volatile concrete classes to avoid the source code dependency on the concrete class to make our code more modular. He mentions the below pattern to handle the volatile dependency in the code.
In the above image author suggest to use the FactoryServiceImpl to create the instance of the ConcreteImpl.
What's the advantage we get in using the FactoryService? Anyway in the main method we will have to create the instance of FactoryServiceImpl and pass to the Application. Instead we can directly create the instance of the ConcreteImpl and pass it to the Application?
What's the advantage we get in using the FactoryService?
The application does not depend on FactoryServiceImpl nor ConcreteImpl. The advantage is that if you want to test the application class you can easily mock the FactoryService just by providing a test/mock implementation.
Since the application class does not depent on the concrete implentations, it is also not dependent on the dependencies of those classes. E.g. the FactoryServiceImpl might contain a dependency to an external service that it passes to the ConcreteImpl when it creates it - could also be a database. Maybe the FactoryServiceImpl uses a fancy framework that you don't want the application to "indirectly" depent upon.
Anyway in the main method we will have to create the instance of FactoryServiceImpl and pass to the Application. Instead we can directly create the instance of the ConcreteImpl and pass it to the Application?
Yes you could create a ConcreteImpl and pass it to the application, BUT Uncle Bob talks about volatile objects in chapter 11. This means that the application creates ConcreteImpl on the fly when it needs it. Maybe a ConcreteImpl is stateful and belongs to a user request. It might also be possible that the factory takes arguments that it uses to create a ConcreteImpl and this arguments change depending on the application state. Thus the application must create a new ConcreteImpl whenever the this state changes. Thus you can not create one instance in the "main" method.

Prism use of discovered service

Suppose a Prism version 8 WPF module has a ViewModel which needs to call on a service.
the service implements IService, but there exists a number of implementations of this service. Each implementation is a file (class library), possibly as a IModule (see below).
The user shall be able to configure which file to use either by configuration or by a folder's content.
Obviously(?) I am thus thinking of Module discovery by creating the right type of ModuleCatalog while "bootstrapping" the application and the service could thus be contained in this module.
If the call is a void call ("fire-and-forget") I guess I could simply use EventAggregator (implementing the service as an observer), however the call returns a value.
What is the best approach solving this?
(I would like to avoid writing my own assembly "discovering/loading" of some kind of a swappable service implementation dll file)
If you can inject IEventAggregator, you can inject IService, can't you?
If no module registered an implementation, you'll get an exception. If more than one module did, the last one wins (with unity as container, at least).

Per-Request DependencyResolver in Web API

In MVC, a ModelValidatorProvider is instantiated and called to validate a model on each request. This means that in a DI environment, it can take dependencies on objects scoped within a single request, such as a Unit of Work or Database context. In Web API, this appears to have been significantly changed. Instead of being instantiated per-request, the ModelValidatorProvider appears to be long-lived and instantiated within the application startup. The WebAPI then caches the results from the ModelValidatorProvider per-type, meaning that the ModelValidator cannot take any dependencies from DI.
I am trying to implement my ModelValidator to use a factory using a Service Locator (please, no automatic 'anti-pattern' comments!). This would allow me to construct an internal validator object within each request, which would be able to take dependencies from the container. However, I cannot get hold of a Dependency Resolver or container scoped to the current request from within this ModelValidator which is essentially scoped as a Singleton. I've tried to use GlobalConfiguration.Configuration.DependencyResolver, but this only returns globally-scoped services (from the root scope, also mentioned here)
I'm working in Autofac, so an autofac-specific solution would be suitable (e.g. MVC has AutofacDependencyResolver.Current, which internally uses DependencyResolver.GetService). There is no equivalent available in the WebAPI integration, presumably because of the reason mentioned above where the global DependencyResolver only returns globally-scoped services.
The reason I'm trying to do this (as well as for my own use) is to implement the Web API integration for FluentValidation, which currently does not exist. There have been two attempts so far, but neither of these handle the Dependency Injection issue and instead result in a single static ModelValidator.
Things I've tried so far:
Using GlobalConfiguration.Configuration.DependencyResolver (returns objects from the root scope)
Taking a dependency on Func<IComponentContext> (always returns the root context)
In an answer which has since been removed, it was suggested to remove IModelValidatorProvider service from the Web API config. This had to be done using reflection since the interface and the implementing classes are all defined as internal, but it did make the validators work better (because the ModelValidator was constructed per request). However, there is a significant performance hit to doing it this way due to the use of reflection to check for validators on the model and every property it has, so I don't want to take this option.
Filip W's answer suggests using HttpRequestMessage to get the Dependency Scope, but I've not found anything such as HttpRequestMessage.Current which would provide access to this object from within a long-lived object - if that could be achieved I believe everything would fall into place.
To get current dependency scope, you have to use (surprise, surprise :) GetDependencyScope() of the current HttpRequestMessage (more about which you can read up on MSDN) instead of GlobalConfiguration.
I blogged about Web API per-request dependency scope a while ago - that should be helpful.

Dynamically creating generic services around Data Repositories in Spring 3.1

I've gotten the basics of Spring more or less down (I think) and I'm trying out new things. Currently, I'm trying to figure out a way not to have explicitly write a service class for each entity/repository if that service is just going to be extending a generic service class.
What I'd like to be able to do is, after the Entity and Repository beans are loaded, loop through them, check to see if a bean named [Model Name]Service exists and, if it does not, create a new instance of my generic service class, pass in the Repository object, and then register this service in the applicationContext.
Is this possible and if so, what is the best way to do it? I've been trying to figure out the PostProcessors, but the one that I think would actual work (BeanPostProcessor) doesn't seem like the appropriate place to do this.
Thanks for your time

Should service layer classes be singletons?

I am using Spring framework. Should my service classes be created as singletons? Can someone please explain why or why not? Thanks!
Yes, they should be of scope singleton.
Services should be stateless, and hence they don't need more than one instance.
Thus defining them in scope singleton would save the time to instantiate and wire them.
singleton is the default scope in spring, so just leave your bean definitions as they are, without explicitly specifying the scope attribute.
You can read more about scopes in the spring docs.
Spring is easier to use if you stick with singleton-scoped beans. Singletons are its "default position", if you like. Yes, it supports other scopes (using scope="xyz" in the XML file), but it makes things harder to use and hurts performance.
Essentially, unless you have a good reason to do otherwise, stick with singletons.
You need mostly singletons. (Spring default.) Singletons must be thread-safe, because parallel requests will use the same single instance. In fact, they must be completely stateless, because it can be destroyed and recreated at any time.
If you need to keep track of state inside of your bean (you should not, this should be in the database or stored in the request), you will get many instances of the same type of bean, memory usage goes up with the number of requests, whereby with singletons you will still have just one instance.
Even if you scope you beans to a request, they must still need be at least thread-safe (requests coming from the same browser at the same time).
Service layer should be Singleton, otherwise for every incoming request a new object will be created and these objects are heavy contains business logic and lots of line of code. They must be Singleton.

Resources