How would one typically implement a service layer in an MVC architecture? Is it one object that serves all requests to underlying business objects? Or is more like an object that serves different service objects that in their turn interact with business objects?
So:
Controller -> Service -> getUserById(), or:
Controller -> ServiceManager -> getUserService() -> getUserById()
Also, if the latter is more appropriate, would you configure this ServiceManager object in a bootstrap? In other words, register the different services that you will be needing for your app to the service manager in a bootstrap?
If none of the above is appropriate, what would help me get a better understanding of how a service layer should be implemented?
Thank you in advance.
The way I read this question, there's really two things that should be answered:
A) I would prefer splitting "Service" into "CustomerService" and "OrderService", in other words grouped by domain concepts.
B) Secondly I'd use dependency injection to get the proper service directly where I need it, so I'm basically using alt 1. The added abstraction in alternative 2 provides no additional value for me, since the IoC container does the important part.
Using a "facade" is one way to go:
"A facade is an object that provides a simplified interface to a larger body of code"
I personally prefer #2, and yes, it would generally be configured in a bootstrap, or the dependencies would be resolved using some sort of IoC container to give you the actual concrete instances.
I would also like to comment, and yes I understand this is probably more of a personal preference. Try to avoid using the name "Service" layer for these objects. refer to them as repositories or something else. if you use service, that term becomes overloaded ... because then devs are like, "do you mean like, a rest or wcf service?". trust me, we did that with a recent project, and we confuse ourselves all the time when we're talking about where to make code changes :-P
Related
I have been using for a while but still I am confuse on what to include in my controllers specifically "When should I use Model and When to Use Service"?
I am confused if I am making the right thing.
I would suggest to never use models directly into the controllers.. Adopt the repository-pattern which enables the use of dependency injection of services into the controller.. Use Service Layer to contain the business logic.. In this way all the related codes would be onto similar layer.
Reference for repository pattern:
http://heera.it/laravel-repository-pattern#.VuJcVfl97cs
Please don't use model directly in your controller, unless if you are building a very simple application but for a large application, it would be good to use a repository. Kindly take a look at this tutorial https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/
Apologies if this has been somehow already answered somewhere - I can't seem to find an appropriate response to my question. Here goes ...
I am currently working on an app accessible via REST. My current teck stack is as follows:
The presentation layer - exposing the functionality in REST
The service layer - taking care of all the business logic, and
The persistence layer - taking care of all DAOs and database-related affairs.
All of this (including Shiro) is autowored using Spring's IoC.
Shiro is currently wired in the presentation layer, making sure all of the calls are protected. The questions I have are: is this the right approach? Does it make sense to apply it to the service layer and, even more so, to the persistence layer?
Many thanks.
The great thing about shiro, is that it can be used at any level. The only thing that really is needed is the idea of a logged in user. In a web framework, this would normally use standard the standard servlet HttpSession to bind it, but that is not necessary.
In our application, we use it at the presentation level to check whether the user has the appropriate rights to view front end pages.
At the business logic level, we call stuff like SecurityUtils.getSubject().isPermitted("somepermissionstring") in custom logic to make sure the user can't call a method when a button is accidentally made visible for that user.
In the frontend code we use the same idea as the business logic.
It works like a charm for us.
So to answer your questions (IMHO):
is this the right approach? -> Yes
Does it make sense to apply it to the service layer -> Yes, if you need very strict security checks!
and, even more so, to the persistence layer? -> Maybe. You have to ask yourself if the security on the service layer might not be could enough, for example if you expose the persistence layer to some code that doesn't go through the service layer. We do not secure the persistence layer as we only access it via our service layer.
I am using spring 3.0 with annotation which i am creating dao interface , then dao implementation class,
then creating service interface and then creating service implementation class.
and using object of service implementation into controller. this process is too lengthy.
can i use only dao class and directly use it in controller?
#service
#controller
public class MyController { ... }
You can but you really really really shouldn't. If you have any plans of putting this code into production, then you need to keep your layers well defined. This is because each layer has a different responsibility.
Your DAO layer is responsible for all database access. It doesn't care what object you want, what you want to do with it, and when you want it done. It only cares about how it's done.
Your Service layer is responsible for what you want to do to your objects. It contains all of your business logic, convenience methods and may use multiple DAO's inside a single service. Your service layer is where you handle your database transactions as well.
Your controller layer is responsible for how you want to show your data to the user. It only contains services and minimal logic concerned with how to display the data returned by your service layer.
I think there are 2 distinct questions being asked here :
Is it really necessary to have all three layers : web layer, service layer, and DAO ?
and :
Do Spring beans necessarily need to implement and interface and to bve (auto)wired by interface rather thant concrete class ?
The answer to both is the same : it is not a necessity, but it is strongly recommended for anything other thant trivial projects.
For the first question, yes it is better so separate concerns in different layers. However I must admint that my controllers sometimes access the DAOs directly for simple read-only tasks in some projects. Sometimes the service layer seems like too much when all it does is to map the DAO methods. However I always use a service layer for transactional business logic that actually modifies the data.
For the second question : Spring can, without problem, instantiate and inject beans that don't implement any interface. However you will start to have problems if you use more advanced stuff linked to aspect-oriented programming, the most common being the #Transactional annotation. In this case Spring has to create proxies to your objects, and it is all simpler to create proxies of interfaces. Ohterwise it has to manipulate bytecode and it introduces limitations.
Perhaps more importantly, "programming to an interface" is a good practice regardless if you are using Spring or not, or even Java or anothrer language. A simple google search will bring up many good articles on this, or SO questions such as this one.
So again, while you can live well without both things in the short term, both will make your life much better in the long term.
I have seen this line of code in several tutorials for using Unity in asp.net mvc3. I was under the impression that Service Locator is an anti-pattern and not best practice. Is this Service Locator something other than the anti-pattern defined, or is this line of code / this implementation considered bad practice.
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(Container));
Old question, but for the benefit of others:
While I absolutely agree with the mantra "Service Location is an anti-pattern", there are definitely exceptions to that rule.
When you use Dependency Injection (like Unity) then, yes, certainly don't use ServiceLocator and only use constructor injection for all your service classes. (Also don't use "new" for anything other than value objects like DTOs.)
However, there are cases where you simply can't use constructor injection and then the only way to get access to a service is to use a workaround to access your Unity container directly, and in such cases, ServiceLocator is a good standard way to accomplish that. This is the case when the class isn't instantiated by you (or more specifically, it isn't instantiated by Unity) but by the .NET framework for example.
A few simple examples of where ServiceLocator might be useful, is to get access to services registered in your Unity container from:
an implementation of a WCF IEndpointBehavior or IClientMessageInspector
an implementation of a WPF IValueConverter
or you may not necessarily even want to get access to "services" from the class, but you simply want to write code that is unit-testable, but for some reason the class can't be instatiated at all (or not easily) because it would normally be constructed by the .NET Framework, so you extract your custom code into a class that is testable, and resolve it in the non-testable class using the ServiceLocator.
Note that this line is not ideal:
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(Container));
The ServiceLocator.Current property is going to execute the delegate provided every time you access Current, i.e. a new UnityServiceLocator is going to get created every time. Instead, you probably want to do this:
IServiceLocator locator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => locator);
If you create a framework which is designed to be container agnostic the service locator (although it should be a No-Go in an application) is an additional layer of indirection that allows you to swap out Unity for something different. In addition the use of the service locator does not enforce the use of DI for applications that use that framework.
It is the same anti-patten that people talk about. All that line is doing is setting the service locator provider to be an instance of UnityServiceLocator, i.e. to use the Unity implementation of the ISerivceLocator. Optionally if you would like you can have your own implementation is IServiceLocator and use that instead of UnityServiceLocator.
Using Service Locator is considered a bad practice for various reasons as listed here
I am a big fan of Dependency Injection and the Play Framework, but am having trouble seeing how the two could be exploited together.
There are modules for Spring and Guice, but the way that Play works makes it hard for me to see how DI could be beneficial beyond some quite simple cases.
A good example of this is that Play expects JPA work to be done by static methods associated with the entity in question:
#Entity
Person extends Model {
public static void delete(long id) {
em().find(id).remove();
}
//etc
}
So there is no need for a PersonManager to be injected into controllers in the way it might for a Spring J2EE application. Instead a controller just calls Person.delete(x).
Obviously, DI is beneficial when there are interfaces with external systems, as the concrete implementation can be mocked for testing etc., but I don't see much benefit for a self-contained Play application.
Does anyone have any good examples? Does anyone use it to inject a Manager-style class into Controllers so that a number of operations can be done within the same transaction, for example?
I believe from this sentence you wrote:
"Does anyone have any good examples? Does anyone use it to inject a Manager-style class into Controllers so that a number of operations can be done within the same transaction, for example?"
that before answering the DI question I should note something: transactions are managed automatically by Play. If you check the model documentation you will see that a transaction is automatically created at the beginning of a request, and committed at the end. You can roll it back via JPA or it will be rolled back if an exception is raised.
I mention this because from the wording of your sentence I'm not sure if you are aware of this.
Now, on DI itself, in my (not-so-extensive) experience with DI, I've seen it used mainly to:
Load the ORM (Hibernate) factory/manager
Load Service classes/DAOs into another class to work with them
Sure, there are more scenarios, but these probably cover most of the real usage. Now:
The first one is irrelevant to Play as you get access to your JPA object and transaction automatically
The second one is quite irrelevant too as you mainly work with static methods in controllers. You may have some helper classes that need to be instantiated, and some may even belong to a hierarchy (common interface) so DI would be beneficial. But you could just as well create your won factory class and get rid of the jars of DI.
There is another matter to consider here: I'm not so sure about Guice, but Spring is not only DI, it also provides a lot of extra functionalities which depend on the DI module. So maybe you don't want to use DI in Play, but you want to take advantage of the Spring tools and they will use DI, albeit indirectly (via xml configuration).
The problem in my humble opinion on the static initialization approach of Play! is that it makes testing harder. Once you approach the HTTP vs Object Orientation problem with static members and objects that carries the HTTP message data (request and response) you make a trade of having to create new instances for each request by the ability of make your objects loosely coupled with the rest of your project classes.
One good example of a different design are servlets, it also extends a base class but it approaches the problem with a single instance creation (by default, because there are configurations that enable more instances).
I believe that maybe a mix of the two approaches would be better, having a singleton of each controller would give the same characteristics of a full static class and would allow dependency injection of some kinds of object. But not the objects with request or session scope, once the controller would need to be created every new request. Moreover it would improve testability by inverting the control of dependency injection, thus allowing arbitrary injection points.
Dependencies would be injected by the container or by a test, probably using mocks for the heavy stuff that much likely would already have been tested before.
In my point of view, this static model pushes the developer away from testing controllers because extending FunctionalTest starts the application server, thus paying the price of heavy objects like repositories, services, crawlers, http clients, etc. I don't want to wait a lot of objects to be bootstrapped just to check if some code was executed on the controller, tests should be quick and clear to make developers love them as their programming assistant/guide.
DI is not the ultimate solution to use everywhere... Don't use DI just because you have it in your hands... In play, you don't need DI to develop controllers/models etc... but sometimes it could be a nice design: IMO, you could use it if you have a service with a well know interface but you would like to develop this service outside Play and test it outside play and even test your play project with just a dummy service in order NOT to depend on the full service implementation. Therefore DI can be interesting: you plug the service loosely in play. In fact, this is the original use case for DI afaik...
I just wrote a blog post about setting up a Play Framework application with Google Guice. http://geeks.aretotally.in/dependency-injection-with-play-framework-and-google-guice
I see some benefits, especially when a component of your application requires a different behavior based on a certain context or something like that. But I def believe people should be selective about what goes into a DI context.
It shows again that you should only use dependencies injection if you really have a benefit. If you have complex services it's useful, but in many cases it's not. Read the chapter about models in the play-documentation.
So to give you an example where you can use DI with play. Perhaps you must make a complex calculation, or you create a pdf with a report-engine. There I think DI can be useful, specially for testing. There I think the guice-module and spring-module are useful and can help you.
Niels
As of a year and some change later, Play 2.1 now has support for dependency injection in controllers. Here's their demo project using Spring 3, which lays it out pretty clearly.
Edit: here's another example using Guice and Scala, if that's your poison.