Is the DAO—Data Access Object—a commonly used pattern in .NET? I've always used DAOs as a way to provide access to my data layer. For example I might have a thin interface over my EntityFramework ObjectContext exposing all of my ObjectSets as IObjectSet.
Complex queries would then be exposed by DAOs, each of which with a dependency on this interface. I might have a ProductDAO that exposes methods like GetProductsOnSale() or GetInfrequenlySoldProducts(). My controllers or presenters would then use these methods, which would likely be virtual to allow stubbing specific results for unit tests.
So is this a commonly used idiom in .NET? For some reason the overwhelming majority of examples I see online using this pattern are based on Java. Even this question on DAO best practices is tagged as Java and not C#.
There's nothing wrong with using something from another community, I just have a slight fear that everyone around me is doing things differently...
It is a common idiom in .NET. I have used it and have seen it used in many places.
It is built into the framework - see the System.Data namespace - many of the classes are base classes for specialized providers (SQL Server, Oracle, MySQL etc...) and operations are executed on the base classes.
However, what you are describing sounds more like the Repository Pattern to me, not simply the use of Data Access Objects.
This is also used in many projects, though is not built into the framework.
I use the DAO pattern extensively.
You mentioned the Entity Framework; to that I would add that I find DAO much better than DataSets and DataTables, which are too much like a database an not enough like an object for my tastes. For example, DataRows can't be added to more than one data table, so I can't pass around subsets of the loaded data to different objects without moving them to a container that wasn't built to contain them. (I.e., it seems like a DataRow should be in a DataTable, but they can only be in one DataTable at a time.) DataRowViews are clunky and not nearly as intuitive as adding entity objects to another list.
My biggest recommendation on the usage of the Repository pattern for encapsulating data access (which indeed is a very good pattern), is to be able to create a generic repository. But to create a very smart generic repository that gives you basically live wiring to immediate access to all standard CRUD operations, along with access to the complex query construct that you won't expose past you ISomeService facade.
The most important thing about using a generic repository, is you want it to be based on constructor injection and not based on inheritance. This way you can compose your SomeService to be dependent on many generic repositories that it would need to fulfill a meaningful business domain boundary.
I wrote an indepth blog on this concept. Creating a common generic and extensible NHiberate Repository version 2. While this blog post is specific in reference of NHibernate you can take the same core concepts and apply them to almost any DAO.
Note with some tools, like Entity Framework, Linq2Sql and RavenDB to name a few, they expose very refined repositories themselves and might not necessarily benefit from adding an additional wrapper.
Related
I am building an application using DDD principles. I am now thinking about the namespace structure in the core of my application. Please see the idea below:
Company.Application.Core.Entities
Company.Application.Core.ValueObjects
However, I cannot find a single example of an application on GitHb, which follows this convention. Is there a specific reason not to follow this naming convention?
I also have a base class for entities i.e. Company.Application.Core.Entities.Entity and a base class for value objects i.e. Company.Application.Core.ValueObjects.ValueObject
The alternative option is to put all Value Objects and Entities in: Company.Application.Core
Your approach will work, but such composition tells story about your code focused on DDD Building Blocks, not about immanent features of your domain. In DDD we want to show important things about domain, the technology issues are not the most important concerns anymore.
I suggest creating following namespaces:
YourCompany.YourApplicationName.YourParticularBoundedContextName.Application
here you can keep all Application Scope building blocks i.e. Application Services and DTO's which are used to transfer parameters to Application Services and return data from them.
YourCompany.YourApplicationName.YourParticularBoundedContextName.Domain
this is the namespace where you will create subnamespaces for Domain Scope building blocks.
YourCompany.YourApplicationName.YourParticularBoundedContextName.Domain.AggregateName
each Aggregate have its own namespace in which there are Aggregate Root class, Entities and VOs used internally in this Aggregate, Repository interface, Aggregate Factory if needed etc.
I don't know if in C# it is possible, but in Java there is another advantage of having separate package (namespace) for Aggregate - you can make Aggregate Root class public and all other Entities and VOs that are internally used as package scope, so they will not be visible outside package (namespace). This way you build public API for your Aggregate that no one can break, because there is a guardian: the compiler :)
YourCompany.YourApplicationName.YourParticularBoundedContextName.Infrastructure
here is a place for repositories' implementations (each in subnamespace of corresponding Aggregate)
Base classes can be kept in:
YourCompany.YourApplicationName.Domain
and even kept in separate project as you can try to reuse it in another application.
What is the advantage? When working with code you are focusing on features and domain rather than on technological aspects. You will more frequently have to cope with problems like "how does this process flow look like" than "I want to see all my Entities and VOs at once", so let your code structure support this. Separating Entities (Aggregates parts actually) and VOs (also Aggregate parts) into separate namespaces you lost information what is working with what. You can simple end with big ball of mud, because you will reuse something that shouldn't be reused.
Please look at:
https://github.com/BottegaIT/ddd-leaven-v2
it is a sample project in Java with packaging done this way. Maybe it will help you.
Another example is:
https://github.com/VaughnVernon/IDDD_Samples
which is a sample for Vaughn Vernon's book about DDD.
There is also article that can be useful:
http://www.codingthearchitecture.com/2015/03/08/package_by_component_and_architecturally_aligned_testing.html
Using separate namespaces for your Entity types (that map to database tables etc.) and your DTO types (used for passing data between client and server layers of your application) is pretty standard practice, even if .Entities and .ValueObjects aren't particularly common choices. I don't think it's worth worrying about too much as long as you use them consistently.
I have created quite a few projects where my business logic has been directly accessing my data layer. Since its the only way I have been setting up my MVC projects, I cannot say for sure where the system has been lacking.
I would, however, like to improve on this. To remove many return functions from my controllers, there are 2 ways I see to achieve the same goal.
Including these return functions as methods of the model classes(doesnt make sense, since the datacontext would need to be initialized within every model).
Using a repository
After reading up a bit on repositories, I haven't come across any instances where "Thinning your controllers" may be a 'pro' to using a repository(a generic repository, could be related to this).
For an understanding of the answer I am looking for, I would like to know if, besides the above mentioned reason, I should use a repository. Is there really a need for a repository?In this case, my project will only be reading data (Full CRUD functionality wont be needed).
There is definitely a need for a repository. Every class should only have one real responsibility where possible; your controller's job is simply to 'give' information to the view. An additional benefit to this is if that if you do create a repository layer then, providing you make interfaces for them, you can make your solution a lot more testable. If your controller knows how to get data from a database (past using a repository - or similar) then your controller is "doing" more than one thing, which violates the single responsibility principle.
I used to use a generic repository pattern using the library SharpRepository, however I found that I needed more fine-grained control over what each of my repositories had access to (for example, there were some repositories I did not want to have mutation control and only be read-only). As a result I switched back to using non-generic repositories. Any half-decent IOC tool will be able to register your repositories based on convention (i.e, IFooRepository maps to FooRepository), so the number of classes is not really a factor.
As a commentor mentioned your title doesn't really sum up your question, so I'll summarize it for other answer authors:
Is there a benefit in using the repository pattern to simplify the controller?
at moment i'm working with few third party repository; these repositories allow me to access to datas only through some specific apis.
What i would to understand is if there is a pattern, that i should use, to abstract each api of each repository for mapping them under an unified datamodel; so that i can query datas using linq, regardless about underlying repository.
Ps :
I'm not interested in all crud operation i would only read queries results, i have no need to edit data (in any way).
Thanks in advance for help.
Your needs are a bit contradictory.
What i would to understand is if there is a pattern, that i should
use, to abstract each api of each repository for mapping them under an
unified datamodel;
Yes, take a look at Adapter, Facade and Bridge in a less degree (all of them are described in GoF). More general it relates to some unified contract (your Repositrory) and model translation. In such case I recommend to look at Anti-Corruption Level pattern from DDD, and also other DDD patterns related to model translation.
The point I confused with is
so that i can query datas using linq, regardless about underlying
repository.
Repository semantic is in hiding of technical details, thus you are working with Repository abstraction like In-memory collection. Actually, relying on ability of all Repository implementations to correctly translate and efficiently use your linq-like queries is a bit naive. Moreover it can be a sufficient limitation for separate (independent) evolution of your App and third-party-repositories.
Finally, as you are working with interface as with a public contract, all implicit technical or implementation logic assumptions (about how something is implementend in nutshell) lead to tight coupling with all consequences. But, if you still want to use LINQ, you can create wrappers for third-party repositories and implement your own LINQ-to-YourRepoTechs provider, but I think it's not worth to be done.
If your third-party repositories provide also technical-specific API, I would recommend to create autonomy service (Web) wrappers for them for 1) encapsulating of technical API difference, 2) translating model with respect to your needs. And to forget about LINQ.
It will be more robust and flexible.
I am currently refactoring my code for a web application developed using ASP.NET MVC3 with C# and Razor. One of the pattern I am using in order to better structure my application is the Repository pattern, which, besides being a really useful pattern, is also a frequent matter of discussion within the developers' community.
In this context I found an article by Fredrik Normen which states that, according to the definition of Repository,a repository class must provide actual entities (for instance List in .NET) and not queriable objects (IQueriable in .NET). Instead in the NerdDinner tutorial from ASP.NET MVC official website they use IQueriable when the Repository has to provide multiple instances of the same object and the actual entity when the repository has to provide a single instance of the object.
What is the most correct approach to use when modeling a repository class/interface according to the Repository pattern?
Thanks
Francesco
In my opinion this sort of thing is detrimental to the use of your time. ;-)
In theory, your repository should return objects or traditional collections of them, yes. However, even the definition of the repository pattern you link to uses the term "collection-like interface". Certainly, an IQueryable<Entity> is a 'collection-like' interface, yes?
In practice, I almost never think about the distinction... but I always try to put all of the querying code in the repository. I'd say 90% of my collection-based repository methods return traditional collections, while the other 10% return something based on IQueryable<>. The exceptions usually have to do with paging; so I can get the totals from the query down the line if needed, and not have to get that info early if I don't need it. It's a little lazy, but it works for me.
But I do think it's a good idea to always try to return traditional collections, because that will mean you are encapsulating all of your querying in the repository, which is where it should be. I would recommend just not to get too caught up in the extreme levels of adhering to someone's idea of what the requirement is for pattern-X
Opinions will differ on that, as you've already found. For small scale applications it's probably OK to let your repositories expose IQueryable.
One thing that you certainly should not do is pass IQueryable to your views. Make sure your views receive only materialized objects and collections (like List or arrays).
This way if an error exists in a query somewhere, it will occur in the controller (or repository) and not in your view. This enables you to test the queries and handle errors gracefully.
I need to design a Data access layer DAL .Net Enterprise library version 3.5 Data access application block (DAAB)
In my application,I've various logical modules like Registration, billing, order management, user management,etc
Am using C# business entities to map the module objects to database tables and then return the List collection to the client.
I would like to design my DAL in such a way that if tomorrow we decide to use some other data access framework we should have minimal code change.
Given this, how do i design my class structure?
I thought I would have a class DbManagerBase which would be a wrapper over existing .net DAAB
This class DbManagerBase would implement an interface called IDbManagerBase which would have public methods like ExecuteReader, ExecuteNonQuery, etc.
The client class ie. RegistrationDAL,UserManagermentDAL would have the following code inside each of its methods:
IDbManagerBase obj= new DbManagerBase()
obj.ExecuteReader(myStoredProcName)
.
.
.
is this a good OOPS design?may i know any better approach please?or do i need to use inheritance here?
Can i have all the methods in DbManagerBase class and RegistrationDAL,UserManagermentDAL classes as static?I guess,if i've methods as static then the above interface code wont make any sense...right???
To truly abstract the DAL I'd use the repository pattern.
To answer a few of the questions:
Can i have all the methods in
DbManagerBase class and
RegistrationDAL,UserManagermentDAL
classes as static?
I would probably go with a non-static approach cause it gives the flexibility to better control instantiation of the DALs (eg. you could create instances of them from a factory), also it will allow you to have two DALs in place that are talking to different DBs in a cleaner way. Also you will not need to create an instance of the DbManagerBase in every object since it would be an instance member.
Regarding IDbManagerBase having ExecuteReader, ExecuteNonQuery and obj.ExecuteReader(myStoredProcName)
I would be careful about baking the knowledge about database specific concepts in too many places. Keep in mind some DBs to not support stored procedures.
Another point is that before I went about implementing a DAL of sorts I would be sure to read through some code in other open source DALs like NHibernate or Subsonic. It is completely possible they would solve your business problem and reduce your dev time significantly.
If you are looking for a small example of a layered DAL architecture there is my little project on github (it is very basic but shows how you can build interfaces to support a lot of esoteric databases)