MVC Repository pattern correct business logic location - asp.net-mvc-4

I am using MVC4,EF5, repository pattern and Unity IoC.
Where should the logic code block be placed?
inside the repository of the specific model
the controller
or by extending the partial class of the model? as a static function?
In my application each controller holds an instance of the unit of work. In case the logic will be held inside one of the repositories or inside a partial class, thus requiring to send the unit of work as a parameter. What would you recommend as best practice?
thanks :)

As GraemeMiller highlights, controllers should be absent of business logic. I think that a repository should be fairly light in terms of business logic, too. Dino Esposito recommends a similar pattern to GraemeMiller, in that the controller hands-off the viewmodel to some kind of co-ordinator that uses various other classes to do its job, generating a modified viewmodel or re-directing to another controller as appropriate. Your co-ordinator could be dependent on a unit of work or it might establish one itself. I'd favour the former.

Related

Implementing localization in DDD pattern - Infrastructure/Persistance Layer?

I'm working on a Blogging platform in .NET Core and one of the key requirements is to have different translations based on the user's selected language. It's clear to me that majority of this part belongs to the UI layer, but I want to let bloggers submit different translations of their posts by themselves.
So far I modified my Domain that it now contains the Language property and I also created Localized attribute to mark properties that are multilingual. In my approach I want to keep all localization-related logic in the Infrastructure layer so it saves/loads proper translations to/from another table containing translations for Localized properties automatically without the Application layer (or services) knowing about it.
I'm also implementing UnitOfWork pattern and normally I would use repositories through it, like in a following way: UnitOfWork.BlogPosts.Add(post) and after all operations are done: UnitOfWork.CommitChanges(), but I assume that now UnitOfWork would contain both repositories: for BlogPost and for Localization and the whole logic of saving/loading localized data would need to be implemented in a UnitOfWork so instead I would have to call a method that manages both repositories, like this: UnitOfWork.AddBlogPost(post) (also IUnitOfWork interface would require these methods).
So my question is: is it a good design appraoch and is UnitOfWork a proper place to implement such logic? I want to keep it as automated as possible and if it doesn't cause any issues that I'm currently not aware of - to keep it directly in a persistance layer.
Edit: My second idea would be to simply keep the two repositories in UnitOfWork and implement saving/loading BlogPost + Localization in an Application layer (in commands handlers and queries using CQRS pattern). But unfortunately this way I would have to implement the same logic for saving/loading for every command and query...

Converting the interfaces in hierarchical structure in OOD

I have a question about Facade design pattern. As i started learning design patterns from the book: Elements of re-useable object -oriented-software, there is a good explaination of what it is and how it solves the problem.
This Picture comes from that book:
Problem:
Suppose i add some extra functionality in the subsystem for which Domain is an Facade/interface. With this design, i think it's not possible to add extra functionality in the subsystem without changing the Domain class?
Second, suppose i use an abstract class Domain(to create a hierarchical structure) and delegate all the requests to it's subclasses so that whenever i want to add new functionality , i simply extend my new class/subsystem with Domain(abstract), would that be wrong or still i will have a Facade structure?
Same thing happends in Adapter pattern. We can have different kind of adapter and instead of hard-coding one class , can we create such an hierarchial structure without violating any OOD rule?
The facade as well as the adapter design patterns are part of the so called "wrapper" patterns (along with decorator and proxy). They essentially wrap certain functionality and provide a different interface. Their difference is on their intent:
facade: is used to provide a simple interface to clients, hiding the complexities of the operations it provides behind it
adapter: allows two incompatible interfaces to work together without changing their internal structure
decorator: allows new functionalities to be added to an object statically or dynamically without affecting the behavior of objects of the same class
proxy: a class (proxy) is used to represent and allow access to the
functionality of another class
If your components "in the back" add new functionality and you want your facade to expose this functionality, you would have to adjust your facade to do so.
If you have the Domain class (facade in your scenario) as an abstract class that others extend, you do not have a facade, you have whatever inheritance you created with your classes. Simply put there is no "wrapping" for achieving the intent of the facade pattern.
With this design, I think it's not possible to add extra functionality in the subsystem without changing the Domain class?
True. However, the changes you make may (or may not) affect the client (Process) class. If you add a new method to the Façade, it won't break the "old" clients. Although it's not its explicit intention (which is to hide complexities of a sub-system), Façade can provide a stable interface to its clients that can be extended. When I say interface, I don't mean a Java or C# interface. It's a programming interface.
A real-world example is the JOptionPane Façade in Java/Swing. Check the Java doc at the link I put and you'll see that some of its methods existed in 1.4, some in 1.6, etc. Basically, since this class is part of a Swing library, it had to remain stable so old clients of it's interface would not break. But it was still extended with new functionality by simply adding new methods.
I would say this is how Façades are typically extended, not with sub classing or hierarchy. Hierarchies are difficult to maintain, because they are brittle. If you get the abstraction wrong (the root of the hierarchy), then it affects the entire tree when you need to change it. Hierarchies make sense when the abstraction in the hierarchy is stable (certain).
The Adapter pattern has hierarchy because an Adapter adapts a method to work with several variants of a service that cannot be changed. You can see examples of several stable (abstract) services such as tax calculation, accounting services, credit authorization, etc. at https://stackoverflow.com/a/13323703/1168342.

Repository Pattern - Structuring repositories

I am trying to use repositories in my MVC program designs and I have run up against a problem on how to best structure them.
as an example, say I have an object USers and I have a UserRepository which has functions like getUser(int id), saveUser(Dal.User model) etc...
So If in my controller I have EditUser and I want to display a view that will have a user details input form. so I can do something like this:
User user = _userRepository.getUserDetails(userId);
The benefit being that my controller just deals with processing HTTP requests, and business logic is moved to repositories, making testing etc easier
So, say I want to display a drop down list of possible roles this user could have in my system, ie client, admin, staff etc
is it ok to have a function in the _userRepository called getPossibleUserRoles() or should I have a seperate _roleRepository with a function getRoles() ?
IS it a bad idea to inject a repository for every entity you encounter into your controller? or is it a bad idea to mix entities inside your repositories, making them cluttered.
I realise I have presented a very simplistic scenario, but obviously as systems grow in complexity you are potentially talking of 10s of repositories needing to be instantiated in a controller for every page call. and also possibly instantiating repositories that are not being used in current controller methods simply to have them available to other controller methods.
Any advice on how best to structure a project using repositories appreciated
is it ok to have a function in the _userRepository called
getPossibleUserRoles() or should I have a seperate _roleRepository
with a function getRoles() ?
Let's say you have some controllers call:
_userRepository.getUserDetails(userId);
but they never call:
_userRepository.getPossibleUserRoles(userId);
Then you are forcing your controllers to depend on methods they do not use.
Sot it's not just ok, you should split this.
But if getUserDetails and getPossibleUserRoles are chosive (sharing same entity, sharing same business logic etc..).
You can split this without changing implemantation of userrepository beside of creating new class for Roles.
public class UserRepsitory : IUserRoles, IUserRepository
{
}
I realise I have presented a very simplistic scenario, but obviously
as systems grow in complexity you are potentially talking of 10s of
repositories needing to be instantiated in a controller
If a constructor gets too many parameters, there is high posibility SRP violation. Mark Seemann shows how to solve this problem in here.
In a short way: While you are creating a behaviour, if you use always 2 or more than repositories together. Then, these repositories are very close. So you can create a service and orchestrate them in this service. After that, you can use this service as a paremeter beside of using 2 or more repositories in your controller constructor.
is it ok to have a function in the _userRepository called getPossibleUserRoles() or should I have a seperate _roleRepository with a function getRoles() ?
Both solutions are acceptable but consider how you're going to control the proliferation of repositories and methods on those repositories. IMHO, the typical repository usage scenario tends to end-up with too many repositories with too many methods on each. DDD advocates a repository per aggregate root. This is a good rule of thumb... if you're following DDD principles.
IS it a bad idea to inject a repository for every entity you encounter into your controller? or is it a bad idea to mix entities inside your repositories, making them cluttered.
Inject volatile dependencies, so yes, inject a repository for every entity your controller needs. However, once you start injecting more than four dependencies, chances are you've missed an abstraction somewhere in your design. Some solve this problem with RepositoryFactory but this, arguably, introduces the problem of opaque dependencies and, IMHO, fails to convey the class's real dependencies, reducing its usability and self-document-ability.
Take a look at using query objects rather than repositories (https://lostechies.com/jimmybogard/2012/10/08/favor-query-objects-over-repositories/, etc.) and take a look at using orchestration/mediation (http://codeopinion.com/thin-controllers-cqrs-mediatr/) in your controllers. I think you'll find a better design emerges that will help you with your design issues.

Should models be able to access my searcher class?

I have a few questions about "best practices" in my application structure. I make use of skinny models, and have service layers which do most (all) of the database interaction. The models call the service layer when they need a database transaction.
I also have a factory class which can return forms, models, and service layer classes. This factory class may also return a "search" class which acts as a very simple DBAL and is used by my service layer.
This search class has helper methods such as getAll() and getById().
I'm slightly confused about which parts of my application should have access to the search class; currently my model uses the static factory to build the search class when it needs to retrieve an entity by it's ID. Should my models instead be calling my service layer to make this call, thus negating the need to use my factory class to return the searcher?
I guess I don't like the idea that my database can potentially be accessed from multiple parts of my application, when really I'd rather everything need to go through my service layer first.
Tips and feedback are much appreciated!
I would end up creating a SearchService (which implements an interface i.e. ISearchService) class which the model, or any other code, that wants to access the Searcher would interact with.
This way you keep a clear separation from the Searcher class, or factory, which could change in the future. The other benefit is that, by having all the search related code in the SearchService, it becomes a lot easier for devs to understand the code, since they know that search related code is in the SearchService, rather then dotted around the codebase, calling factory methods, etc.
Also, by using an ISearchService, you allow yourself the option to use Dependency Injection, which is a nice way of having your object initialised for you, and not having to worry about implementation changes.
That's just my preference though, rather then this being a right/wrong way to do things.

What's a good name for a façade class?

A little background: We're building a library/framework for working with scientific models. We have an interface Model which defines the operations that a model must implement, which is pretty minimal. That is: the Model interface defines the contract of a model from the point of view of a model implementor.
The framework adds a bunch of other functionality around the model, but right now client code has to access that functionality by using a bunch of other classes, such as ModelInfo, ModelHost, ModelInstance, etc.
In our application that uses this framework, we don't want to actually have to deal with all this mechanism of running models, etc. So we've decided to use the façade pattern to wrap up the framework functionality in an easy-to-use object. (We've already applied this pattern to other parts of the framework, with good success.)
Here is the question: given that we already have an interface Model, what would be a good name for the façade class? The Model interface is the contract between the framework and the model implementation, and the new class will define the contract between the framework and the client application.
Or, more generally: when we have an abstraction provided by a library or framework, how can we name the "two sides" of the abstraction so as to clearly identify the "provider" and "consumer" interfaces to the abstraction?
(If it matters, for this project we're using Java 6.)
I know this seems trite, but... have you considered using "ModelFacade" as the class name for the facade class? I think with documentation that indicates that the interface was already named Model, it seems relatively straightforward, and makes it very clear which design pattern you're using.
How about *Provider and *Consumer? I think you said it yourself in your question. Perhaps *Producer and *Consumer is a better match?
In discussions within our team, another option has been proposed: we can rename the existing Model interface to something else, and just call the new façade Model. In fact, they can both be called Model right now, because they will live in separate packages. (Although I'm not a fan of identically-named classes in different namespaces.)
Sounds like ModelInfo, ModelHost, and ModelInstance should all be members of Model.
See https://softwareengineering.stackexchange.com/questions/316840/is-it-bad-practice-to-name-a-class-with-a-facade-suffix for why you generally shouldn't name classes with the specific implementation used. Basically, some day you may want to use a different implementation of Model, which happens to not be a facade.
PureMVC uses a singleton named ApplicationFacade and registers all the models with methods like registerProxy which are defined in IFacade