Can we use repository pattern and Unit Of Work in ASP.Net WEB API.? - asp.net

I'm Developing ASP.Net Web Api. For developing WEB API, Do I need Repository Pattern and Unit Of Work, what are the benefits they have and when can we use them ?
suggestions are appreciated.

You can most definitely use the repository pattern in WEB API.You just need to do some research and find out the problem it's trying to solve and if it's the right fit for your application.Repository is a good choice when:
You have a lot of CRUD(Create Read Update Delete) functionality in your application that needs to be performed on different entities(SQL tables for example) and you want to centralize data access and make future additions of new entities easy as application evolves.
You want to have a substitution point for unit testing.
You want to apply a domain model to simplify business logic.
You want to implement and centralize a caching strategy for the datasource.
You can use repository pattern without unit of work. To check if you need UOW ask yourself this question - Does my application require transactional support?If yes, then implement a UOW, otherwise just use repository pattern.
Have a look at the links below, this helped me in the past to implement repository and unit of work patterns:
Generic repository in C#
CRUD operations using repository pattern and Unit Of Work

Related

Repositories and Entity Framework

I am building a web api for my application and right now i am looking for ways to design my data access layer.
At the end, the application should be able to support a very large number of client and a very large number of queries.
I have heard about entity framework but i have two concerns with it:
I have been told by many that entity framework is not the best when it comes to performance, and performance is something that i can't afford to neglect.
I am only starting to build the application and i'm still looking for developers to join me, if i start with entity framework now, i might want/need to change an orm/library (because of the reason above or any other reason) or even a database technology in the future.
Repositories are a great way to abstract the data access layer and make it invisible to the business layer, so if one day i want to change the DAL/Database technology, i won't have to touch the business, only change the repositories.
Still, i have read a lot about how combining entity framework with the repository pattern is a bad practice.
I am really confused... and i have few questions.
Should i use entity framework? Performances is an important thing to me.
Should i combine it with repository pattern? If not, what do i do when i want to change the database technology/orm?
I have practice with using the repository pattern with native sql client (running native sql queries) but i don't have any practice with using orm's, at least not in .net
Is it really a bad thing for big application to use native sql queries and wrap them with repositories?
It is really important for me to begin writing my application in best way possible (applying all the best practices) so i won't have much struggle in the future.
Thanks,
Arik
Ad.1) Yes, Entity Framework is dead slow - BUT - when used out of the box, if the developers has deep knowledge of Entity Framework, what it does behind the scenes, how to optimize the queries - it can be as fast as your more low-lewel own implementation of data access.
Ad.2) If you want to change the ORM or the Database technology - that is not a matter whetever you use EF or not, it's a matter of the architecture you will design for the software.
Ad.1) see former Add.1, if performance is really important, I personally would go with low-level SqlDataReader, altough as I sad, it's possible to use EF in a performant way.
Ad.2) I don't see nothing bad in combining the repository pattern with EF, in small applications it may be an overhead, because the EF is basically an implementation of an repository pattern, so you would get a "double repository pattern", but it allows you to abstract away the coupling with EF
Ad.3) I don't think it's a bad way - but it depends obviously on the application.
I think that using a repository pattern is a good idea and a sort of wayout if you have some performance issues.
About Dapper the question is why Dapper is more performant than EF and NHibernate. No Lazy Load, no DML, easy mapper and so on. If you want DML (I do) and sometimes Lazy Load you could have a mixed approach. Repository Pattern + EF + Dapper.
My approach actually is Repository Pattern + EF + very few query (massive update and delete and few select - EF writes huge SQL statements also for simple queries - ). To map the select you can include Dapper (I don't), do it by hand (manually mapping or use the features inside EF - but there are some limitations - or write something generic). Usually I map it manually but I wrote also a mapper based on EF Mapping
Entity framework Code First - configure mapping for SqlQuery
I used it for few times and actually I don't use it anymore.

Advice on refactoring Business/Data Logic in preparation for migrating WebForms to MVC

I'm looking some advice on to a strategy for migrating from Asp.Net WebForms to MVC. I currently have a solution of approx 60 projects in the following format:
Solution
ProjectA.DataModel
ProjectA.Business
ProjectA.Web
ProjectB.DataModel
ProjectB.Business
ProjectB.Web
Framework.Core
Framework.Common
…etc
All data models are Entity Framework 6 using database first (.edmx) and T4 templates. Data access code is mixed between both the Business and Web (WebForms) projects. The code base has grown organically initially from a sole developer through to a small team which explains some of the bad practice in terms of SOC however we want to try take this opportunity to rectify this.
I want to start moving towards a full MVC solution and feel the first thing to do is ensure any data access logic currently residing in the Web projects is pushed to the Business layer to get Separation of Concerns. Researching into a best practice for this has taken me towards the Unit of Work and Repository patterns however further reading seems to be suggesting this is overkill.
What would be the best approach to refactoring my Business and Data Layers with the current Web Forms model in readiness for MVC. Secondly is an accepted approach for migration to MVC to bring in Views to the existing WebForms solution to create a Hybrid or to create a new MVC project, reference my existing BAL and DAL and start building the application UI from scratch?
In regards to Entity Framework, everything appears to be moving towards a CodeFirst approach. Is this something we need to be planning for if we want to go forward with a best practice approach?
We are currently a very small team and want to try make best possible re-use of our existing projects and refactor as much as possible to get into a position of beginning to move towards MVC.
Any thoughts on how I can begin to approach this is appreciated.
Thanks
Nasty app you have there. Anywas, first thing to rembmer is that MVC is a UI pattern. So in a properly designed app the swtich from WebForms to Mvc would mean just change the UI layer.
I want to start moving towards a full MVC solution and feel the first thing to do is ensure any data access logic currently residing in the Web projects is pushed to the Business layer to get Separation of Concerns
No! Data access logic should be in the DAL (hint: it's an acronym), not BL, not UI. Persistence Only. BL and UI would ask the DAL to save/retrieve their objects via Repository. And btw, EF deals with db only. Don't make the mistake to build your business objects on top of Ef Entities. One models business concept and behaviour, the other model database access. They're usually not compatible. When dealing with anything but persistence, ignore that you have a db or an ORM.
Researching into a best practice for this has taken me towards the Unit of Work and Repository patterns however further reading seems to be suggesting this is overkill.
It's overkill ONLY if you a have a very simple app that you don't care about maintaining it. I know is hard to believe but probably over 80%(more or less random number) of devs still don't understand how to properly implement the Repository pattern that's why it becomes useless for them. In a nutshell, the repo uses the EF but it's not built on top of it. The repo 'transforms' business/ui objects to EF entities and vice versa.
The repo interface should never expose IQueryable or the fact that you're using a db in the first place. So, no generic repositories and no exposing of EF entities. Also, the Bl/UI shouldn't create queries (it would mean they know how the data is stored - a DAL implementation detail), that's the repository's job. THe higher layers just tell the repository what they want, never how to do it.
Secondly is an accepted approach for migration to MVC to bring in Views to the existing WebForms solution to create a Hybrid or to create a new MVC project, reference my existing BAL and DAL and start building the application UI from scratch?
Although you can mix WebForms and Mvc in the same project, it's better not to do it (less headaches). Start the mvc app from scratch then port the web forms pages to it.

Using SqlCe as a database and unit tests with Sqlite

At the moment I am using SqlCe as a database for my project and doing unit tests with Sqlite because of its simplicity(Such as allow to use Inmemory). I just wonder, in the future this may lead to a dispute or oddity?
If using a different persistence mechanism inside of your unit tests causes you a problem, then the problem would likely be caused by:
Your unit tests
Your general application architecture
The tests that you write for an object should not depend on any way that their dependencies are implemented, doing so automatically means your unit tests turn into integration tests.
You should design your objects using the concept of Persistence Ignorance, which means that they are implemented in such a way so that their implementation does not depend on how the underlying datasource is implemented. A common method for achieving PI inside of enterprise applications is to use the Repository Pattern. This abstracts the interface your objects use to access the datasource from the underlying implementation of the datasource itself. What this means is, in theory, you can create new providers to different datasources without having to change the implementation of your objects that depend on them.
For example:
Let's say that you have an entity called Customer which you save inside of a SqlCe database. You could create an interface called ICustomerRepository that is implemented by a SqlCeCustomerRepository which you use inside of your main application. That way in your unit tests, you could swap it out for a SqlLiteCustomerRepository if you found that to be an easy way to create a mock datasource. To keep things even simpler, you could just create an InMemoryCustomerRepository that used List<T> under the hood to store and retrieve your objects. The point being it doesn't really matter HOW the datasource is implemented, as long as it conforms to the contract you set up on your repository interface.
The benefits of this pattern also reach beyond unit testing, and into general maintenance of your application. Suppose you want to scale up your architecture and use SQL Server instead of SQL CE, using an abstraction such as a repository would help limit the amount of change required in your system in order for this to happen, leading to less development time, less bugs, and happier customers.

Implementation of a ASP.NET based portal-like application

There is the requirement, to write a portal like ASP.NET based web application.
There should be a lightweigted central application, which implements the primary navigation and the authentication. The design is achieved by masterpages.
Then there are several more or less independent applications(old and new ones!!), which should easily and independent be integrated into this central application (which should be the entry point of these applications).
Which ways, architectures, patterns, techniques and possibilities can help and support to achieve these aims? For example makes it sense to run the (sub)applications in an iframe?
Are there (lightweighted and easy to learn) portal frameworks, which can be used (not big things like "DOTNETNUKE")?
Many thanks in advance for you hints, tips and help!
DON'T REINVENT THE WHEEL! The thing about DotNetNuke is that it can be as big or as small as you make it. If you use it properly, you will find that you can limit it to what you need. Don't put yourself through the same pain that others have already put themselves through. Unless of course you are only interested in learning from your pain.
I'm not saying that DNN is the right one for you. It may not be, but do spend the time to investigate a number of open source portals before you decide to write your own one. The features that you describe will take 1000s of hours to develop and test if you write them all from scratch.
#Michael Shimmins makes some good suggests about what to use to implement a portal app with some of the newer technology and best practice patterns. I would say, yes these are very good recommendations, but I would encourage you to either find someone who has already done it this way or start a new open source project on codeplex and get other to help you.
Daniel Dyson makes a fine point, but if you really want to implement it your self (there may be a reason), I would consider the following components:
MVC 2.0
Inversion of Control/Dependency Injection (StructureMap for instance)
Managed Extensibility Framework
NHibernate (either directly or through a library such as Sh#rp or Spring.NET
A service bus (NServiceBus for instance).
This combination gives you flexible user interface through MVC, which can be easily be added to via plugins (exposed and consumed via MEF), a standard data access library (NHibernate) which can be easily configured by the individual plugins to connect to specific databases, an ability to publish events and 'pick them up' by components composed at runtime (NServiceBus).
Using IoC and DI you can pass around interfaces which are resolved at runtime based on your required configuration. MEF gives you the flexibility of defining 'what' each plugin can do, and then leave it up to the plugins to do so, whilst your central application controls cross cutting concerns such as authentication, logging etc.

How to test asp.net membership, profile, roles with VS Test Framework?

We're getting some errors, if we try to test something with the asp.net membership framework. It seems that it can't instantiate the asp.net membership environment and so, it can't access all the profiles, users and so on.
Has anybody seen a similar problem? Or is it working for someone?
Cheers,
Steve
If you are depending on external resources such as your database and the configuration files (used when using the ASP.NET membership) you aren't writing very effective unit tests. You will have to keep everything in sync including the data in the database. This because a maintenance nightmare.
If you want to test this way, I recommend setting up your configuration to have membership (you can grab this from your application). You then will also want to set up a test database to connect to. It needs to be populated with fake data, so you'll need scripts to make sure the data is consistent.
I would however recommend that you take the approach of doing more proper unit tests. When we refer to a "unit test" we mean testing a very small piece of code at a time. This code should not depend on anything else, so what you need to do is use interfaces and use fakes, stubs, or mocks so that your tests scope is enclosed to a single unit of code.
If you want to go this route I highly recommend reading Working Effectively with Legacy Code. There are also plenty of other books and resources which talk about how to find seams and decouple your code so you're able to test it. Once you get the hang of unit testing you'll be glad you looked into this.
The test framework is looking at the test project's web.config file which likely doesn't have the right configuration. You should really write interfaces around the authentication/membership providers and write some dummy implementations to test with.
Going on from Benrick's answer - I recommend you take a look at the ASP.NET MVC project - this has examples of the interfaces and wrappers you would need to have to properly unit test your code.
As the comments in the AccountController.cs file state:
The FormsAuthentication type is sealed and contains static members, so it is difficult to unit test code that calls its members. The interface and helper class below demonstrate how to create an abstract wrapper around such a type in order to make the AccountController code unit testable.

Resources