Repository pattern and web api - asp.net-web-api

Hi i learned web api 2 recently and i am working on a sample project now.I am following layered architecture in my project.This is the flow
controller=>Business Layer=>Data Layer
Now i read some article about the repository pattern which sound better nowadays.
i saw the flow like
controller=>services=>repository
Is there any significant difference between the two flows?
As a beginner which style of architecture should i flow?
Can someone help me to understand these patterns?

When you use services with repository you should make it generic and use Unit of Work (UOW) so you don't repeat yourself with CRUD actions on every entity. Then add some object relational mapper (ORM) like Entity Framework. It is prefered that you also use domain objects for storing your logic there, and make the services return data transfer objects (DTO), because best practice is to keep your services small and clean. Then you also need to include some mapping tool/logic to map DTO to Domain objects.
And you see where this is all going. Suddenly you have far more complexity and obstructions than you need. Because only one thing that customer care about is quality of your product not some fancy architecture.
But as project grow it is much more important to have proper architecture, automatic tests etc. , so it is valid in large projects. If you want to experiment and learn it is great opportunity, but if you have running application in production, i would rather not make that big changes.
TLDR: they are both valid

Related

Moving from JSF/Spring to Rest API + Angular

There is a project that is built using JSF with Spring Integration.
See https://www.tutorialspoint.com/jsf/jsf_spring_integration.htm to get an idea.
JSP is used for the html templates. Managed beans (part of JSF) make use of Spring beans as a managed property, which in turn drive business logic. The goal is to rip apart this project and split it into a RESTful service and Angular front end.
What is the best way to do this without re-writing everything. Which components can I get rid of, and which components can be re-used? If I use Spring Boot for building the REST API, can I re-use the Spring beans?
Edit: I am new to most of these technologies.
Exposing your domain model through REST should be relatively straight forward using Spring/JPA, whatever. You should learn about DTOs and especially as it relates to problems about "Lazy Initialization" under Hibernate/JPA/Spring Data, etc.
Secondarily understand the concept of views into the domain model. E.g., shipping looks at the database differently than marketing. Same database, different "facades" or business layers with different set of DTOs.
Conceptually, reproducing a JSF front end in Angular is something that is both "the same thing" and "completely different" at the same time. The key difference, IMHO, will be the JavaScript concepts and paradigms underlying Angular/React/Vue or whatever you want to use on the Front End.
Consider that an AngularJS/React/Vue front end might be better off running on top of node.js in a separate container or server, and might have different databases that it accesses on its own such as loyalty points or currency conversion, etc. Don't be afraid to let the frontend folks "be" the application instead of the backend folks. On the backend, try not to lose information. For example, if a customer adds 3 items, then changes 1, then places the order, that's 3 separate pieces of information, not 1 order. This is important for business analytics and customer service, which are business facing services as opposed to client facing services.
As a Java developer I tend to feel Angular/JS developers do a completely different and non-overlapping job than me. I feel the same way towards HTML/CSS folks. As such, I don't recommend you try being both, you will stretch yourself too thin. However, a good working knowledge on a smaller project, such as you are suggesting, is certainly useful.
Welcome to SO. Your post will probably be closed/ignored for being to broad, etc. Very specific questions and answers are what this site is about. GL.

Microservices, Dependencies and Events

I’ve been doing a lot of googling regarding managing dependencies between microservices. We’re trying to move away from big monolithic app into micro-services in order to scale organizationally and be able to develop faster and with multiple teams working in parallel.
However, as we’re trying to functionally partition the monolith into the microservices, we see how intertwined business logic and data really is. This was not a problem when we were sitting on top of one big DB and were able to do big relational joins. But with microservices, this becomes a problem.
One solution is to make microservice-A go to 5-10 other microservices to get necessary data (this is equivalent of DB view with join). Another solution is to make microservice-A listen to events from 5-10 other services and populate local storage with relevant into (this is an equivalent of materialized view). Either way, microservice-A is coupled with 5-10 other services, and if new info is needed in microservice-A, the some of the services that it depends upon might will need to be release prior to microservice-A. Please note that microservice-A is itself depended upon by other services. Bottom line, we end up with DISTRIBUTED dependency hell.
Many articles advocate for second solution – i.e. something along the lines of Event Sourcing, Choreography, etc.
I would appreciate any shared experiences, recommendations and insights.
Philometor.
While not technically an "answer", I can definitely share some of my observations and experiences. Your question concerning services calling other services for database operations reminded me of a project where an architect sold senior management on the idea of "decoupling" persistence from the rest of the applications by implementing hundreds of REST interfaces in what essentially was a distributed DAO pattern in front of a very large enterprise database. The project ended up exactly the way I predicted - a dismal failure.
Microservices aren't about turning a monolithic application into a distributed monolithic application. In my example project above, the monolith was turned into a stove-piped, fragile, chaotic mess, with the coupling only moved to service contracts instead of Java class method signatures, and with a performance hit so bad the application was unusable. Last I heard they are still running their original monolith.
Microservices should be more of a vertical partitioning of your application and not a horizontal one. In my opinion it's better to think in terms of business function partitioning rather than "converting" an existing monolith. There's no rule that determines how big a microservice must be, but it should be big enough to do one complete synchronous function without needing to directly depend on outside services (as much as possible) to complete its work. If a microservice performs a complex business function that affects 50 tables, so be it! It owns those many tables. Ideally if a service goes down, it should affect only that business functionality it's responsible for, and not directly affect other services. As you can see, this thinking is the complete opposite from that which produced the distributed mess in my project example.
Not only do you need to ensure that the motivation behind replacing monoliths with microservices is sound, but also you need to step outside the monolith and revisit the actual business and begin partitioning that instead. Like everything else, baby steps are the way to go. Start with one small complete business function, and convert that into a single microservice instead of trying to replace a monolith all at once.

Organizing application in layers

I’m developing a part of an application, named A. The application I want to plug my DLL into, called application B is in vb 6, and my code is in vb.net. (Application B will in time be converted to vb.net) My main question i, how is the best way for me to organize my code (application A)?
I want to split application A into layers (Service, Business, Data access), so it will be easy to integrate application A into B when B is converted to vb.net. I also want to learn about all the topics like layered architecture, patterns, inversion of dependency, entity framework and so on. Although my application (A) is small I want to organize my code in the best way.
The application I’m working with (A) is using web services for authenticating users and for sending schema to an organization. The user of application B is selecting a menu point in application B and then some functions in my application A is called.
In application A I have an auto generated schema class from an xsd schema. I fill this schema object with data and serialize the object to a memory string (is it a good solution to use memory string, I don’t have to save the data yet), wrap the xml inside a CDATA block and return the CDATA block as a string and assign the CDATA block to a string property of a web service.
I am also using Entity framework for database communication (to learn how this is done for the future work with application B). I have two entities in my .edmx, User and Payer.
I also want to use the repository pattern (is this a good choice?) to make a façade between the DAL and the BLL.
My application has functions for GeneratingSchema (filling the schema object with data), GetSchemaContent, GetSchemaInformation, GenerateCDATABlock, WriteToTextFile, MemoryStreamToString, EncryptData and some functions that uses web services, like SendShema, AuthenticateUser, GetAvalibelServises and so on.
I’m not sure where I should put it all?
I think I have to have some Interfaces like IRepository, ISchema (contract for the auto generated schema class, how can I do this?) ICryptoManager, IFileManager and so on, and classes that implements the interfaces.
My DAL will be the Entity framework. And I want a repository façade in my BLL (IRepository, UserRepository, PayerRepository) and classes for management (like the classes I have mention above) holding functions like WriteToFile, EncryptData …..
Is this a good solution (do I need a service layer, all my GUI is in application B) and how can I organize my layers, interfaces, classes an functions in Visual Studio?
Thanks in advance.
This is one heck of a question, thought I might try to chip away at a few parts for you so there's less for the next guy to answer...
For application B (VB6) to call application/assemblies A, I'm going to assume you're exposing the relevant parts of App A as COM Components, using ComVisibleAttributes and similar, much like described in this artcle. I only know of one other way (WCF over COM) but I've never tried it myself.
Splitting your solution(s) into various tiers and layers is a very subjective/debatable topic, and will always come down to a combination of personal preference, business requirements, time available, etc. However, regardless of the depth of your tiers and layers, it is good to understand the how and the why.
To get you started, here's a couple articles:
Wikipedia's general overview on "Multitier Architectures"
MSDN's very own "Building an N-Tier Application in .Net"
Inversion of Control is also a very good pattern to get into right now, with ever increasing (and brilliant!) resources becoming available to the .Net platform, it's definitely worth infesting some time to learn.
Although I haven't explored the full extent of IoC, I do love dependency injection(a type of IoC if I understand correctly though people seem to muddle the IoC/DI terms quite a lot). My personal preference for DI right now is the open source Ninject project, which has plenty of resources online and a reasonable wiki section talking you through the various aspects.
There are many more takes on DI and IoC, so I don't want to even attempt to provide you a comprehensive list for fear of being flamed for missing out somebody's favourite. Just have a search, see which you like the look of and have a play with it. Make sure to try a couple if you have the time.
Again, the Repository Pattern - often complemented well by the Unit of Work Pattern are also great topics to mull over for hours. I've seen a lot of good examples out on the inter-webs, and as many bad examples. My only advice here is to try it for yourself... see what works for you, develop a version of the patterns that suits you best and try to keep things consistent for maintainability.
For organising all these tiers and layers in VS, I recommend trying to keep all your independent tiers/layers in their own Solution Folders (r-click the Solution, Add New Solution Folder), or in some cases (larger projects) there own solutions and preferably an automated build service to update dependent projects with up to date assemblies as required. Again, a broad subject and totally down to personal preference. Just keep an eye out when designing your application for potential upcoming Circular References.
So, I'm afraid that doesn't even slightly answer your question, but hopefully provides you with some resources to check out and a few hours of reading.
Good luck!

web development - MVC and it's limitations

MVC sets up clear distinction between Model, View and Controller.
For the model, now adays, web frameworks provides ability to map the model directly to database entities (ORM), which, IMHO, end up causing performance issues at runtime due to direct database I/O.
The thing is, if that's really the case, why model ORM is so pupular and every web frameworks want to support it either organically or not.
To a web site has huge amount of traffic, it definitely won't work. But what's the work around? Connect directly to database is definitely not a wise solution here.
What's your question?
Is it a good idea to use direct db access from webpages?
A: No.
Is it a good idea to use ORM's?
A: Debatable : See How can I design a Java web application without an ORM and without embedded SQL
Is it a good idea to use MVC model?
A: Yes - it has nothing to do with "Direct" database access - it's about separating your application logic from your model and your display. (Put simply).
And the rationale for not putting database logic inside webpages has nothing to do with performance - it's about security/maintainability etc etc. Calling a usp from a webpage is likely to be MORE performant than using an ORM, but it's bad because the performance gain is negligible, and the cons are significant.
As to workaround: if you mean how do you hook up a database to a web application...?
The simplest way is to use something like Entity Frameworks or Linq-Sql with your Model - there are plenty of examples of this in tutorials on the web.
A better method IMO, is to have a separate Services layer (which may be WCF based), and have all the database access inside that, with DTO's transferring the data to your Web Application which has it's own ViewModel.
Mvc is not about orm but about separation of display logics and business logics. There is no reason your exposed model needs to be identical to you database model and many reasons to ensure that the exposed model closely matches what is to be displayed.
The other part of the solution to scale well would be to implement caching in the control and be able to distribute load on sevaral instances.
I think #BonyT has given a good answer, (and I've voted for it :) ), I'd just add that:
"web frameworks provide the ability to map the model directly to database entities (ORM), which, IMHO, ends up causing performance issues at runtime due to direct database I/O"
Even if this is true, using an ORM can solve a lot of problems with a model being easy to update and translate back and forth between a database. Solving a performance hit by buying extra web servers or cloud instances is much cheaper than having to buy extra developers or extra hours in development to solve things other people have already written ORMs to do for you.

Linq to SQL layers/architecture?

I am sorry for my question may looking a old repetitive questions but I as I am starting Linq to SQL I want to discuss how many layers (architecture) should I use ?
I am working on web mostly web sites and small to medium scale web applications. I understand dividing application into layers help its maintainanace and enhancement but frankly I want some balance way which give me rapid development and code reuse-ability as well. I cannot spare so much time on unwanted management of layers.
Before I was using 4 layers (business objects, BLL,DAL and user itnerface.) I became confuse on it as different people have described different layers. Please guide me what and how many layers I should use ? Thanks
Don't use the layer architecture. Use the onion architecture.
The most important aspect from architecture perspective is the separation of concerns. Separation of concerns leads to clean code, easy maintenance, extensible, etc. That said, I recommend to base your decisions based on the following criteria:
Try to architect your system in a loosely coupled way. Use messaging instead of RPC as messaging is reliable, scalable, asychronous, loosely coupled, etc. You can either use MSMQ or NServiceBus (for service bus based architecture).
Create layers based on the separation of concerns concept. For e.g. you can go for typical 3 layered architecture which will have just UI layer, business logic layer (business rules+workflow) and data access layer or more granular such as UI layer, services layer (facade), business logic layer, data access layer, etc. Using IoC / Dependency injection will make life easy as none of the layers will have direct dependency. Moreover, it promotes unit testing easy as you inject mocks instead of the real implementations for the unit test. There are so many IoC frameworks available (NInject, Autofac, Castle Windsor, Structure Map, etc...)
Try to use EF instead of Linq to SQL as the later works only with SQL, while the EF works with any database. Moreover, in my opinion, EF is where microsoft is innovating and I would assume that Linq to SQL may be retired one day.
Great question haansi. This is something that I have wrestled with quite often when building small to medium sized sites. Finding that balance of creating a architecture that gives you the greatest flexibility and allows for rapid deployment is what I think we all need to strive for in all of our work.
With that being said, I have found that using the Repository Pattern to be quite helpful with LINQ to SQL projects. I couple that with the Model View Presenter pattern (for WebForms or other projects) and it provides a great foundation for reuse with minimal layers.
My Webform calls a Presenter class, which in turn is responsible for populating the View. To populate that View the Presenter can call N number of Repositories. The Repository is where you encapsulate your DataContext class and your LINQ to SQL calls. These calls return the model classes.
One huge benefit to this regardless of the size of the app is that get great re-use out of your Repository, you get to maximize the use of LINQ and you have used some patterns that other software developers could easily read and support.
Another big benefit is that you now have created a simple architecture that can benefit from using Unit Testing to test from the Presenter back to the Repository without a ton of effort.
Good luck!
I decided to use one layer (DAL + BLL) for small projects and for large applications will use Different layers for DAL & BLL. I will use Linq in DAL and funtiosn will return IQueryable.

Resources