Must the repository have persist functionality? - c#

In Fowler's book "Patterns of Enterprise Application Architecture" there is no mention of persistent features of the Repository pattern. By "persistent features" I mean such features that update, save, add or delete entities. Just pure matching mechanism over a set of domain objects.
On the other side, lets take a look at Mike Hadlow's blog post named Using the IRepository pattern with LINQ to SQL. There are concrete persistent methods like insert and delete.
So how should a repository pattern be implemented? Could you guys please point me towards good "true" repository implementations. I'm getting some frustration on this topic.
Thanks in advance! Hope for your help!

A repository should just act like an in-memory collection of data. The nomenclature you choose, whether it be Add or Insert, Delete or Remove, Select or Get, is not important.
You could separate your repository into 2 interfaces, and then have a ReadOnlyRepository for getting / selecting data, and a WriteRepository for adding / updating / deleting data. It doesn't matter. What matters is that your application or business code uses the repository to interact with data as if it was already loaded into memory, so you don't have to craft SQL queries intermingled with business or application code.
Update
Since we're talking about a pattern, there is not a single "true" repository interface or implementation. There can be many different implementations that all follow a similar pattern.

Related

Aggregate Roots DDD/UoW/Repo/Service

I have some questions about the Aggregate Objects for Repositories.
I'm making a Rest Service with DDD/UoW/Repo and Service pattern. Our new cloud web-apps shall use this service. In order to do this, we also have to sync data from the old databases, which are still in production. We created a "SyncService" which read and writes to/from the cloud and down to earth.
In my Rest/DDD-design. And I don't want the business logic to run on these, so in the original test project I have a repository for every model and the endpoints just do some simple validation and push the data straight to the database using the repository.
Let's say I have these entities:
Customer
Order
OrderLine
Article
Database Relationsships:
A customer can have many orders.
An Order can only have one customer.
An Order can have many OrderLine's.
An OrderLine can have one Article.
Questions:
Are all of these aggregates except Article?
And which of these Entities would have a repository?
What would the repository look like?
Should I make endpoints for the "SyncService" to only talk to generic repositories for insertion?
Thanks in advance.
Are all of these aggregates except Article?
I believe it's impossible to answer this question without having access to the business logic and understanding how the whole Domain should look like. E.g. In some system, the Customercould be an aggregate and Order just an entity and in some other backward.
This decision should be made by an architect.
2,3,4. If you are using DDD you access your entities by your aggregates. I'd say the concept of using the repository pattern is optional. In some cases, you can just use pure DB context and e.g. if you are using for example Entity Framework Core you don't have to build extra repository layer over it as it is already a repository by itself. So the answer to these questions would be- it all depends.

Design of Data Access Layer with multiple databases

I have read many posts concerning the issue of having several databases and how to design a DAL efficiently in this case. In many cases, the forum suggests to apply the repository pattern, which works fine in most cases.
However, I find myself in a different situation. I have 3 different databases: Oracle, OLE DB and SQLServer. Currently, there exists a unique DAL with many different classes sending SQL queries down to a layer below to be executed in the corresponding database. They way the system works is that two of the databases are only used to read information from them, and the other one is used to either store this same information or read it later on. I have to propose a better design to the current implementation, but it seems as if a common interface for all three databases is not plausible from an architectural point of view.
Is there any design pattern that solves this situation? Should I have three different DALs? Or perhaps it is possible (and advisable) to apply the repository pattern to this problem?
Answers to your question will probably be very subjective. These are some thoughts.
You could apply command-query separation. The query side integrates directly with your data layer, bypassing any business or domain layer, and the returning entities are optimized for read and project from your databases. This layer could also be responsible to merge results from different database calls.
The command side consists of command handlers, using domain or business entities, which are mapped from your R/W database.
By doing this, the interface that you expose will be more clear and business oriented.
I'm not sure that completely abstracting out the data access layer with custom units of work and repositories is really needed: do the advantages outweigh the disadvantages? They rarely do, because you will you ever change a database technology? And if you do, this probably means a rewrite anyway. Also, if you use entity framework code first, you already have unit of work and an abstraction on top of your database; and the flexibility of using LINQ.
Bottom line - try not to over-engineer/over-abstract things; or make things super-generic.
Your core/business code should never be dependent on any contract/interface/class that is placed in the DAL layer of the application.
Accessing data is something the business/core layer of your application needs to be able to do, and this it should be able to do without any dependency of SQL statements and without having any knowledge of the underlying data access technology.
I think you need to remove any "sql" statements from the core part of the application. SQL is vendor dependent and any dependency to a specific database engine needs to be clean out of you core, and moved to the DAL where it belongs. Then you need to create interfaces that resides outside of the DAL(s) which you then create implementation classes for in one or many DAL modules/classes. Your DAL can be dependent of your core, but not the other way around.
I don't see why the repository layer can't be used in this case. When I have a database which I can only read from, I usually let the name of the repository interface indicate this, like ICompanyRepositoryRead.

Data Access Layer without ORM

I'm coding mmorpg server emulator (hobby project) and i've stopped on writing data access layer. The thing is that i can't use ORM (performance matter). I've read a lot about Repository pattern but it seems like it does not fit well into my project because I'm gonna need methods like: (player db) GetAllByLevel(...), GetByName(...), etc.
I want my application to be database agnostic. (I'm using sql server for now but i would like to add support for mysql later)
Which data access pattern would fit into my project?
Sorry for my bad english.
Edit
One more question. I've read that repository pattern operates on the agreggate root.
I've got 3 tables player, player_friend and player_chest. Player is an agreggate root and if i'm not wrong i should create just one repository (PlayerRepository) that could have methods like: GetFriends([player id], ...), GetChest([player id], ...) and so on.
Am i right?
I've read a lot about Repository pattern but it seems like it does not fit well into my project because I'm gonna need methods like: (player db) GetAllByLevel(...), GetByName(...), etc.
On the contrary. There are a lot of faulty repository pattern examples out (typically leaky abstractions) which teach you wrong. GetAllByLevel is imho a good method since it describes the role of the method quite clear.
I've written about the repository pattern: http://blog.gauffin.org/2013/01/repository-pattern-done-right/. Do also read the abstraction link in the beginning of the article.
The thing is that i can't use ORM (performance matter).
No problem. The repository pattern is used to abstract away the data source, no matter which kind it is.
If you want to use vanilla ADO.NET you can read this blog post: http://blog.gauffin.org/2013/01/ado-net-the-right-way/
One more question. I've read that repository pattern operates on the agreggate root. I've got 3 tables player, player_friend and player_chest. Player is an agreggate root and if i'm not wrong i should create just one repository (PlayerRepository) that could have methods like: GetFriends([player id], ...), GetChest([player id], ...) and so on. Am i right?
No. I would say that Friends is a root too. Read this article about designing aggregates: http://dddcommunity.org/library/vernon_2011
Repository is the way to go. The point is that you can have multiple implementations of the same repository interface, one for sql server another one for oracle or postgresql. You don't necessarily have one generic implementation that supports all possible databases (this would be quite difficult).
The concrete implementation can use any specific features of the concrete dbms to fit your performance criteria.

Design of Business Layer

We are currently revamping our architecture and design of application. We have just completed design of Data Access Layer which is generic in the sense that it works using XML and reflection to persist data.
Any ways now we are in the phase of designing business layer. We have read some books related to Enterprise Architecture and Design so we have found that there are few patterns that can be applied on business layer. Table Pattern and Domain Model are example of such patterns. Also we have found Domain Driven Design as well.
Earlier we decided to build Entities against table objects. But we found that there is difference in Entities and Value Objects when it comes to DDD. For those of you who have gone through such design. Please guide me related to pattern, practice and sample.
Thank you in advance! Also please feel free to discuss if you didn't get any point of mine.
#Adil, this is not an answer to your original question, but I would advise you to revise your decision to roll your own data access layer. You note that you'd like to go to NHibernate: just do it now.
IMO, writing an ORM is a waste of time unless you have some very specific restrictions. There are a wealth of options out there, with hundreds of hours of effort poured into them already. Leverage it! LINQ2SQL, Entity framework, NHibernate, Subsonic, LLBLGen are all good, and there are more out there.
Note too that if you roll your own you won't get to use the goodness that is LINQ without a lot of effort.
As far as layering goes, try not to go nuts: keep the number of layers in check and concentrate instead on building a worthwhile interface between them to guard against your abstractions leaking.
I've seen a number of very "patterned", beautifully layered projects that in use end up with logic everywhere and persistence abstractions leaked all over the place. Keep it simple!
CSLA.NET works pretty well as a base for the business layer.
#Adil,
I'm not very experient user, anyway, this is the kind of model I'm using (also with NHibernate).
GUI - with all the web forms and so on
BLL - The catalogs that are responsible for creating instances of new objects
DAL - The place where classes responsible for interaction with NHibernate are implemented. The NHibernate mapping files are here.
Model - Class Library that is used by the BLL and DAL for data transfer object between.
Different patterns are used. For example, the BLL and DAL have a Factory class that allow access to an interface. The catalogs are Singleton classes. All of the catalogs are accessible using a master Singleton class representing my business logic top object (for example "Enterprise" => "Enterprise.PeopleCatalog".
Anyway, hope it helped...
#AngryHacker, thanks for the tip, could you give an example of CSLA.NET?

ASP.NET C#: Which Design Pattern should I use and why?

I am developing an app in ASP.NET C# and came across the following scenario:
I will have to create some maintenance screens for different entities (tables)
Those entities will basically have the same behaviour within the UI: Search, GetById, Save, Create and GetAll
The entities may have different structure i.e. different properties (fields)
As I am talking about 20 plus admin screens, which design pattern I could take advantage of in order to minimize the amount of code I will have to write?
I though of the bridge pattern but I am a little confused on how to implement it ...
A little bit of the technology background I am using:
ASP.NET classic (n-tier)
LINQ to SQL and DAO objects
SQL Server 2005
For a set of admin screens that are just doing CRUD (Create, Read, Update, Delete) operations and with little in the way of business logic, I'd be quite tempted to more or less eschew design patterns and take a look at asp.net dynamic data. This is especially true if you want to minimise the amount of code you want to write.
This is not a design pattern... but I would strongly suggest using Dynamic Data. Jonathan Carter has some great articles about it: http://lostintangent.com/index.php?s=dynamic+data
If you're really just doing some basic stuff like this: Search, GetById, Save, Create and GetAll, I would recommend you use repositories. If done wrong repositories can get really bad and nasty, but if you're really primarily limited to this set of operations you've basically described a repository with that set of operations.
You'll want to look at ways in which you can extract the extra logic for example of searching so that you're not creating duplicate logic.
Repositories are nice and testable as long as you make sure not to let them get out of control. I give you this warning only because I've seen far too many people create monster classes out of repositories.
The repositories work with your objects. They are basically the intermediary which handles the persistence of your data. This abstraction allows you to hide from the rest of your code how you're persisting your data. In this case the implementations of your repositories will be using LinqToSql as I believe that is what you said you were using.
There are plenty of resources explaining the repository pattern.
What you want is not a design pattern. You are looking for an ORM with scaffolding. I have used and highly recommend SubSonic - http://subsonicproject.com. You can read about its scaffolding features here: http://subsonicproject.com/web-forms-controls/the-scaffold/

Categories

Resources