Is it common practice to hold a repository globally? [closed] - asp.net-mvc-3

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
In repository examples, I see the repository instantiated when the Session opens, which seems as if it is around for the entire Session. In controller actions, the data layer is then accessed through calls to the repository. Is this common practice? Wouldn't it make more sense to be instantiating the repository in an on need basis per action request?
Edit: A more exact scenario.
public class myController : Controller {
IMyRepository myRepository;
public myController(IMyRepository repositoryParam){
myRepository = repositoryParam;
}
public ActionResult someAction(){
MyClass myClass = myRepository.RepositoryAction();
}
}
In this scenario, myRepository is global to myController (note: this is based off an example from Steven Sanderson). I have seen it also defined for all controllers to access, but this is a simple, exact, example. In this example, why would the repository be used globally instead of on a per use basis?

To answer your question, Travis, you should read up a bit on the Repository Pattern. This pattern is used to provide a number of advantages, including:
It centralizes the data logic or Web service access logic.
It provides a substitution point for the unit tests.
It provides a flexible architecture that can be adapted as the overall design of the application evolves.
As to your question: "Is this a common practice?" the answer is, "It should be." but, unfortunately, I don't see it as much as I would prefer.
Now, in your example, you show the repository being created within the context of your controller class. (Please note that this is NOT the same thing as an object being made "global" as you put it. Global means that the object is accessible from any scope. Read more about it here at Wikipedia.)
In any case, one of the advantages is that the repository allows you to change between how you are accessing your data (or even where your data is being accessed) by using the correct, concrete version of the repository. So, you may have:
IRepository - Your interface which the concrete repositories implement.
DatabaseRepository - Accesses your data in a database.
FlatFileRepository - Access your data out of a flat file.
etc.
If you wish to switch to other data sources, it is a simple as swapping out the concrete implementation in your controller. (Please note, there are more advanced and flexible ways of doing this through dependency injection, but that is out of scope of this question, although it does/can play heavily in the repository pattern.)
In any case, say your project team decides "Hey, we're going to switch from storing all our data in flat files to using a database." Well, if you have scattered the instantiations of that specific repository throughout your code, you now have a lot of different areas to fix and update, somewhat negating the advantages of the repository pattern. However, by declaring a member repository of your controller, you just switch from a FlatFileRepository to a DatabaseRepository, implement the new repository, and you are finished! Everybody on the team is happy!
Update: "Why Instantiate a Class Variable?"
To answer that question, you have to think of your two options. The first option is that you could hold a relatively small object in memory. The other alternative is you could instantiate a new object in memory every time that a user needs to access one of your actions causing new memory to be allocated (and deallocated when you leave the scope that the object was in) and requiring more work by the server which is hosting your web app.
If you think about how a website is used, users are hitting those actions on a frequent basis. Every action signifies a portion of your website. If you instantiated every single time you needed the repository, you would quickly give the server a much bigger workload than it actually needs - particularly as your site grows in size. (I am sure other folks can think of other reasons why you would want to do it the way shown in the tutorial vs. instantiation in each individual action.)
And, then, of course, there is the refactoring issue as I mentioned above. That is about "efficiency of making changes" or improving the maintainability.
Hope that helps you a bit more and better answers your question!

Related

Multiple Controllers appropriate with one entity in spring framework

I'm starting to develop website that use the spring framework.I have three controller.There are newCustomerController,editCustomerController and deleteCustomerController.These controllers are mapped with view that use for create update and delete, but I create only customer.
So, I would like to know.Is it appropriate to declare the controllers like this.
Thank
The answer to this question is subjective and maybe more a topic for https://softwareengineering.stackexchange.com/. However, there is something very spring related about it that I would like to comment.
There are a few principles that attempt at guiding developers of how to strike a good balance when thinking about designing the classes. One of those is the Single responsibility principle.
In object-oriented programming, the single responsibility principle
states that every class should have a single responsibility, and that
responsibility should be entirely encapsulated by the class. All its
services should be narrowly aligned with that responsibility
A catchier explanation is
A class or module should have one, and only one, reason to change.
However, its still often hard to reason about it properly.
Nevertheless, Spring gives you means for it (think of this statement as a poetic freedom of interpretation). Embrace constructor based dependency injection. There are quite a few reasons why you should consider constructor based dependency injection, but the part relevent to your question is adressed in the quote from the blog
An often faced argument I get is: “Constructors just get too verbose
if I have 6 or 7 dependencies. With fields only, this is fine”.
Awesome, you’ve effectively worked around a clear indicator that the
code you write is doing way too much. An increase in the number of
dependencies a type has should hurt, as it makes you think about
whether you should split up the component into multiple ones.
In other words, if you stick to constructor based injection, and your constructor turns a bit ugly, the class is most likely doing too much and you should consider redesigning.
The same works the other way around, if your operations are a part of the logical whole (like CRUD operations), and they use the same dependencies (now "measurable" by the count and the type of the injected deps) with no clear ideas of what can cause the operations to evolve independently of each other, than no reason to split to separate classes/components.
It should be better if you define one controller for Customer class and in that class you should have all methods related to customer operations (edit,delete,create and read).

Best practice for passing data to service layer [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am working on a web application in spring following the MVC pattern and was wondering what is considered "best practice" for making a solid service layer. The reason for this question is the following example situation:
A page for editing user information is loaded. After this form is submitted I gather all of its data in my controller method in a specific Command class containing only the data needed for the action that follows (updating the user).
I can think of several situations now to pass this information to my service layer:
Passing the command itself: userService.save(command);
Passing a model class, fetched in the controller: userService.save(user);
Passing both a model class and the command: userService.save(user, command);
Passing all of the parameters individually: userService.save(command.getName(), ...)
In my opinion passing the command class itself looks like the most elegant solution as I can first validate all the values automatically using the framework then pass them to my service. My concern here is that when I call the method from another class (not through my form / controller) I can fill this command object with invalid data, resulting in possible errors in the service layer.
What would you recommend and why?
After seeing your I have the following ideas
Passing the command itself: userService.save(command);
This may not be a goode idea since your Service layer is unnecessarily
dependent on Command object
Passing a model class, fetched in the controller: userService.save(user);
I will vote for this. Service layer only what it really supposed to
know
Passing both a model class and the command: userService.save(user, command);
No. Same as the first option
Passing all of the parameters individually: userService.save(command.getName(), ...)
Hmmmm... not sure.. May be a mainitenance overhead in future.
I think if you want to do the validation, Use validation util classes to do the validation
which can be used for both Service and UI layer. Here a lot validation can be centralized.
In his MVC book, Dino Esposito recommends creating a 'worker' class that takes and returns a viewmodel. The controller calls the worker with the viewmodel and then the worker delegates as necessary. I've not used it in practise but in theory it appears to be a nice solution.
Any option using your Command object will cause trouble. It breaks loose coupling. Now your service layer is tightly coupled with service layer. Please don't do it.
(EDIT: In my answer below, when I say Model for presentation layer I am talking about View Model and for service layer it is the Domain Model)
Sending your Model object looks like a good option. But, it depends on how the model was created. Some times, presentation layer will need a different model structure and the service layer will need a moderatley/completely different structure.
If both layers have different needs, then you need to create 2 model structure. This way service layer's model structure doesn't have to change when presentation layer changed. This is important as the service may have multiple consumers and may not be able to change when presentation layer changes.
If they don't have different structure, I would still create them from service layer point of view as service is the real reusable component here.
A good pattern to follow when dealing with commands in multi-layered systems is to have a CommandBus service that routes your commands to their specific handlers. That way, you decouple your controller from your services (while coupling it with a generic routing system).
commandBus.handle(command);
You must do additional work in configuring the command bus handlers, but it will pay in the long term when you'll be able to reuse that routing information:
commandBus.register(commandType, handlerService);
and you may then be able to move the validation of the commands in the commandBus service (even though this will mean some mixing of concerns for the commandBus)
commandBus.registerValidator(commandType, validatorsCollection);

Static? Repositories MVC3, EF4.2 (Code First)

I'm new to MVC, EF and the like so I followed the MVC3 tutorial at http://www.asp.net/mvc and set up an application (not yet finished with everything though).
Here's the "architecture" of my application so far
GenericRepository
PropertyRepository inherits GenericRepository for "Property" Entity
HomeController which has the PropertyRepository as Member.
Example:
public class HomeController
{
private readonly PropertyRepository _propertyRepository
= new PropertyRepository(new ConfigurationDbContext());
}
Now let's consider the following:
I have a Method in my GenericRepository that takes quite some time, invoking 6 queries which need to be in one transaction in order to maintain integrity. My google results yeldet that SaveChanges() is considered as one transaction - so if I make multiple changes to my context and then call SaveChanges() I can be "sure" that these changes are "atomic" on the SQL Server. Right? Wrong?
Furthermore, there's is an action method that calls _propertyRepository.InvokeLongAndComplex() Method.
I just found out: MVC creates a new controller for each request. So I end up with multiple PropertyRepositories which mess up my Database Integrity. (I have to maintain a linked list of my properties in the database, and if a user moves a property it needs 6 steps to change the list accordingly but that way I avoid looping through all entities when having thousands...)
I thougth about making my GenericRepository and my PropertyRepository static, so every HomeController is using the same Repository and synchronize the InvokeLongAndComplex Method to make sure there's only one Thread making changes to the DB at a time.
I have the suspicion that this idea is not a good solution but I fail to find a suitable solution for this problem - some guys say that's okay to have static repositories (what happens with the context though?). Some other guys say use IOC/DI (?), which sounds like a lot of work to set up (not even sure if that solves my problem...) but it seems that I could "tell" the container to always "inject" the same context object, the same Repository and then it would be enough to synchronize the InvokeLongAndComplex() method to not let multiple threads mess up the integrity.
Why aren't data repositories static?
Answer 2:
2) You often want to have 1 repository instance per-request to make it easier to ensure that uncommited changes from one user don't mess things up for another user.
why have a repository instance per-request doesn't it mess up my linked list again?
Can anyone give me an advice or share a best practice which I can follow?
No! You must have a new context for each request so even if you make your repositories static you will have to pass current context instance to each its method instead of maintaining single context inside repository.
What you mean by integrity in the first place? Are you dealing with transactions, concurrency issues or referential constraints? Handling all of these issues is your responsibility. EF will provide some basic infrastructure for that but the final solution is still up to your implementation.

What are your best practices when using an MVC-based web framework?

A few general questions to those who are well-versed in developing web-based applications.
Question 1:
How do you avoid the problem of "dependency carrying"? From what I understand, the first point of object retrieval should happen in your controller's action method. From there, you can use a variety of models, classes, services, and components that can require certain objects.
How do you avoid the need to pass an object to another just because an object it uses requires it? I'd like to avoid going to the database/cache to get the data again, but I also don't want to create functions that require a ton of parameters. Should the controller action be the place where you create every object that you'll eventually need for the request?
Question 2:
What data do you store in the session? My understanding is that you should generally only store things like user id, email address, name, and access permissions.
What if you have data that needs to be analyzed for every request when a user is logged in? Should you store the entire user object in the cache versus the session?
Question 3:
Do you place your data-retrieval methods in the model itself or in a separate object that gets the data and returns a model? What are the advantages to this approach?
Question 4:
If your site is driven by a user id, how do you unit test your code base? Is this why you should have all of your data-retrieval methods in a centralized place so you can override it in your unit tests?
Question 5:
Generally speaking, do you unit test your controllers? I have heard many say that it's a difficult and even a bad practice. What is your opinion of it? What exactly do you test within your controllers?
Any other tidbits of information that you'd like to share regarding best practices are welcome! I'm always willing to learn more.
How do you avoid the problem of "dependency carrying"?
Good object oriented design of a BaseController SuperClass can handle a lot of the heavy lifting of instantiating commonly used objects etc. Usage of Composite types to share data across calls is a not so uncommon practice. E.g. creating some Context Object unique to your application within the Controller to share information among processes isn't a terrible idea.
What data do you store in the session?
As few things as is humanly possible.
If there is some data intensive operation which requires a lot of overhead to process AND it's required quite often by the application, it is a suitable candidate for session storage. And yes, storage of information such as User Id and other personalization information is not a bad practice for session state. Generally though the usage of cookies is the preferred method for personalization. Always remember though to never, ever, trust the content of cookies e.g. properly validate what's read before trusting it.
Do you place your data-retrieval methods in the model itself or in a separate object that gets the data and returns a model?
I prefer to use the Repository pattern for my models. The model itself usually contains simple business rule validations etc while the Repository hits a Business Object for results and transformations/manipulations. There are a lot of Patterns and ORM tools out in the market and this is a heavily debated topic so it sometimes just comes down to familiarity with tools etc...
What are the advantages to this approach?
The advantage I see with the Repository Pattern is the dumber your models are, the easier they are to modify. If they are representatives of a Business Object (such as a web service or data table), changes to those underlying objects is sufficiently abstracted from the presentation logic that is my MVC application. If I implement all the logic to load the model within the model itself, I am kind of violating a separation of concerns pattern. Again though, this is all very subjective.
If your site is driven by a user id, how do you unit test your code base?
It is highly advised to use Dependency Injection whenever possible in code. Some IoC Containers take care of this rather efficiently and once understood greatly improve your overall architecture and design. That being said, the user context itself should be implemented via some form of known interface that can then be "mocked" in your application. You can then, in your test harness, mock any user you wish and all dependent objects won't know the difference because they will be simply looking at an interface.
Generally speaking, do you unit test your controllers?
Absolutely. Since controllers are expected to return known content-types, with the proper testing tools we can use practices to mock the HttpContext information, call the Action Method and view the results to see they match our expectations. Sometimes this results in looking only for HTTP status codes when the result is some massive HTML document, but in the cases of a JSON response we can readily see that the action method is returning all scenario's information as expected
What exactly do you test within your controllers?
Any and all publicly declared members of your controller should be tested thoroughly.
Long question, longer answer. Hope this helps anyone and please just take this all as my own opinion. A lot of these questions are religious debates and you're always safe just practicing proper Object Oriented Design, SOLID, Interface Programming, DRY etc...
Regarding dependency explosion, the book Dependency Injection in .NET (which is excellent) explains that too many dependencies reveals that your controller is taking on too much responsibility, i.e. is violating the single responsibility principle. Some of that responsibility should be abstracted behind aggregates that perform multiple operations.
Basically, your controller should be dumb. If it needs that many dependencies to do its job, it's doing too much! It should just take user input (e.g. URLs, query strings, or POST data) and pass along that data, in the appropriate format, to your service layer.
Example, drawn from the book
We start with an OrderService with dependencies on OrderRepository, IMessageService, IBillingSystem, IInventoryManagement, and ILocationService. It's not a controller, but the same principle applies.
We notice that ILocationService and IInventoryManagement are both really implementation details of an order fulfillment algorithm (use the location service to find the closest warehouse, then manage its inventory). So we abstract them into IOrderFulfillment, and a concrete implementation LocationOrderFulfillment that uses IInventoryManagement and ILocationService. This is cool, because we have hidden some details away from our OrderService and furthermore brought to light an important domain concept: order fulfillment. We could implement this domain concept in a non-location-based way now, without having to change OrderService, since it only depends on the interface.
Next we notice that IMessageService, IBillingSystem, and our new IOrderFulfillment abstractions are all really used in the same way: they are notified about the order. So we create an INotificationService, and make MessageNotification a concrete implementation of both INotificationService and IMessageService. Similarly for BillingNotification and OrderFulfillmentNotification.
Now here's the trick: we create a new CompositeNotificationService, which derives from INotificationService and delegates to various "child" INotificationService instances. The concrete instance we use to solve our original problem will delegate in particular to MessageNotification, BillingNotification, and OrderFulfillmentNotification. But if we wish to notify more systems, we don' have to go edit our controller: we just have to implement our particular CompositeNotificationService differently.
Our OrderService now depends only on OrderRepository and INotificationService, which is much more reasonable! It has two constructor parameters instead of 5, and most importantly, it takes on almost no responsibility for figuring out what to do.

Repository pattern vs. "smart" business objects [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I see two main "schools of thoughts" when it comes to creating larger-scale enterprise-wide apps on .NET (Winforms, WPF, ASP.NET).
Some folks use the "repository pattern" which uses a repository that knows how to fetch, insert, update and delete objects. Those objects are rather "dumb" in that they don't necessarily contain a whole lot of logic - e.g. they're more or less data-transfer objects.
The other camp uses what I call "smart" business objects that know how to load themselves, and they typically have a Save(), possibly Update() or even Delete() method. Here you really don't need any repository - the objects themselves know how to load and save themselves.
Big question is: which do you use or prefer? And why?
Do you use the same approach in all your apps, or do you have any particular criteria when to choose one approach over the other? If so - what are those criteria?
I'm not trying to start a flame-war here - just trying to find out what everyone thinks about this and what your opinion is, and why you use one (or both) patterns over the other.
Thanks for any constructive input!
I use the repository pattern because of the Single Responsibility Principle. I don't want each individual object to have to know how to save, update, delete itself, when this can be handled by one single generic repository
The repository pattern doesn't necessary lead to dumb objects.
If the objects have no logic outside Save/Update, you're probably doing too much outside the object.
Idealy, you should never use properties to get data from your object, compute things, and put data back in the object. This is a break of encapsulation.
So the objects should not be anemic except if you use simple DTO objects with CRUD operations.
Then separating the persistence concerns from your object concerns is a good way to have Single Responsibility.
Here are two interesting articles I came across
Repository-is-the-new-singleton
The DAL should go all the way to UI
I think the most important side-effect of using the Repository pattern vs. the ActiveRecord pattern is testing and extensibility.
Without having your ActiveRecord object contain a repository itself how would you isolate data retrieval in your test cases? You can't really fake or mock it easily.
Besides testing it would also be much more difficult to swap out data access technologies, for example from Linq-to-SQL to NHibernate or EntityFramework (though this doesn't happen often admittedly).
It really depends on the needs of the application, but when dealing with a complex business model, I prefer ActiveRecord. I can encapsulate (and test) the business logic all in one place.
Most ORM's (EF, nHibernate, etc...) serve as your Repository. Many people consider a layer on top of an ORM that encapsulates all data interaction as a Repository, which I believe to be incorrect. According to Martin Fowler, a Repository encapsulates data access as a collection. So having individual methods for all data retrieval/mutation might be using a Data Mapper or a Data Access Object.
Using ActiveRecord, I like to have an "Entity" base class. I typically use an ORM (repository) with this base class, so all of my entities have a GetById, AsQueryable, Save and Delete methods.
If I'm using more of a Service Oriented Architecture, I'll use a repository (one that masks direct data access or an ORM) and call it directly in my services.

Resources