Composition Root in ASP.NET MVC DDD application - asp.net-mvc

I am reading currently "Dependency Injection in .NET" by Mark Seemann. And I am wondering what would be the best way to compose a DDD ASP.NET MVC application.
In simplified scenario, the general rule of thumb, would be to have Domain Model which would be core of the application, and would not have any dependencies on Data Layer or Presentation. It would expose certain interfaces which Presentation would use (hence dependency) and Data Layer would implement (hence dependency). So it is all nice and clear.
However, now, when we compose the application. Which in case of ASP.NET MVC app we would do in global.asax (http://blog.ploeh.dk/2011/07/28/CompositionRoot). Our composition root will require dependency on all layers, because it needs to register all applicable types.
This makes all dependencies looks messy, now Presentation layer has a project reference to Data Access layer (in VS terms). It is easy for a developer to make a mistake and use types form Data Access layer directly, which would effectively couple those layers.
Is there a clean way to solve this conundrum? It almost would be nice to have the Composition Root outside of the presentation layer, but in MVC that would not be possible.
UPDATE
After asking this question I found a related one:
DAL -> BLL <- GUI + composition root. How to setup DI-bindings?
and it had some interesing solutions. The accepted solution is almost perfect, however I would like the composition root to be outside of presentation layer, and reference presentation layer rather than the other way.
One reason for that is that it is to me more conceptually clear - composition should be on the very top. The other reason is that in my case presentation layer has many DI objects in it already (mostly domain object to view model mappers) and I would like to have them composed in one spot as well.
This thread gave me some ideas though, I think what I am trying to do may be possible.

It is easy for a developer to make a mistake and use types form Data Access layer directly, which would effectively couple those layers.
It's easy to do a lot of stupid things no matter how you try to prevent it. Don't model your application after what the developer may not do. Model it so it's easy to do things correctly.
he accepted solution is almost perfect, however I would like the
composition root to be outside of presentation layer, and reference
presentation layer rather than the other way.
My container has support for what you ask. In each project create a single module which registers everything else:
public class CompositionRoot : IContainerModule
{
public void Register(IContainerRegistrar registrar)
{
registrar.RegisterType<ISomeType, SomeType>();
}
}
In your UI project you simply load all dlls:
registrar.RegisterModules(Lifetime.Scoped,
Environment.CurrentDirectory,
"myproject.*.dll");
That's it (you can also replace most manual RegisterType etc with a single line if you tag your implementations with the [Component] attribute).
https://github.com/jgauffin/griffin.container

Most IoC containers expose the concept of logically grouping together bindings into a module.
Ninject calls these Modules
Structuremap calls these Registries
Windsor calls these Installers
etc
The effect is that only the assembly containing the module needs to know about the concrete implementations, and the composition root only needs to access the modules.
Example (pseudo):
// In data access assembly
namespace MyProject.DataAccessLayer
{
internal class MyRepository : IMyRepository
{
// ...
}
public class DataAccessModule : IModule
{
void Configure(container)
{
container.ForInterface<IMyRepository>()
.UseType<MyReposutiry>()
.Singleton();
}
}
}
// In presentation layer assembly
namespace MyWebApp
{
void Booptstrap()
{
var iocContainer = /* ... */
iocContainer.AddModule(new RepositoryModule());
}
}
Notice that the concrete implementation class of MyRepository is internal. Only the module needs to see it.
The natural extension to this pattern is that each assembly exposes only an IoC module publically, all the other concrete classes are an internal implementation detail.

One way to attain a greater degree of encapsulation is to expose the domain as an HTTP service, with say ASP.NET WebAPI. The ASP.NET MVC solution would then reference this API. There would be no data access dependencies, only a reference to the service. For simplicity, the published language of the API can be extracted into an assembly that could be referenced by the MVC presentation solution. The trade-off of this approach is added moving parts and the steps involved in creating and managing a service.
Additionally, having the configuration you describe is perfectly acceptable. The encapsulation attained by extracting a service might not be worth the price. Developers should have the discipline to prevent leaks of the sort you describe.

I am working on a solution architected in the way the eulerfx describes above (it was a system requirement rather than my own design choice). It will solve your problem, though you may want to consider separating your domain model classes from your domain. In addition you will need another composition root for the web api services, and as he notes, a further layer of mapping from the webcontroller viewmodels (which will have to be shared between the service and the website) to the domain models.
Ive created a few solutions now using the methods described in the Dependency Injection in .NET book and I can say that using the methods described within it has certainly meant better quality, loosely coupled code.
Good luck!

Related

Architecture to use Automapper with database first approach

I have the following Solution structure.
Solution
ProductServiceApi
Business
DataAccess
DTO
Contract
I am using EntityFramework in DataAccess layer. It has the .edmx file and entity classes(e.g. Product). I have my domain classes in DTO layer(ProductDto). I am creating the map in WebApiConfig.cs file. To map the DTO and DataAccess layer entities I have to add a reference to both DTO layer and DataAccess layer in ProductServiceApi.
e.g. Mapper.CreateMap<ProductDto, Product>();
But I think its a bad idea to add a reference to dataAccess layer in my ProductServiceApi.
What should I do to avoid this? Should I add a reference automapper in DTO layer and map the dto and entity there? What is the ideal solution. I have gone through some online tutorials but cannot find a proper solution.
I had prepared quite a lengthy answer to this question but as I re-read it it dawned on me that the answer I had would only mislead you. So here's a shorter answer :)
But I think its a bad idea to add a reference to dataAccess layer in my ProductServiceApi.
If as I suspect ProductServiceApi is a WebAPI Project, then you can't really (and shouldn't anyway) do anything to avoid this; in this case is it's effectively acting as Automapper's Composition Root*, and in order for it to do that, it must have a reference to all of these things - otherwise it cannot compose object mappings for you.
That's perfectly OK and not a problem at all from a design point of view
; you could "kick the can down the road" and do your Mapping configuration in a separate assembly, but then ProductServiceApi will have to reference that assembly meaning by association it is still directly referencing the lower layers.
So whilst there are things that I suspect need attention in your current design and can be discussed further, I don't believe you have a problem with the scenario outlined in this specific question :)
Examples of things that might need looking at
You have a single Contract Layer that I presume contains abstractions...this should be split out into multiple layers each of which contains a cohesive set of abstractions related to one part of the system.
Also, having your Domain objects defined in your DTO Layer sounds a bit odd.
But these are things for another question...
*(I know that Composition Root is more often than not used in the context of IoC libraries however in this case you are composing a Mapping between types which is a kind of IoC so I'm taking the view that the principle is the same).

Is it considered bad design to pass a repository interface as an argument to a method on a domain class?

Our domain model is very anemic right now. Our entities are mostly empty shells, almost purely designed for holding values and navigating to collections.
We are using EF 4.1 code-first ORM, and the design so far has been to shield our novice developers against the dreaded "LINQ to Entities cannot translate blablabla to a store expression" exception when querying against the context during early iterations.
We have various aggregate root repository interfaces over EF. However some blocks of code in the impls seems like they should be the domain's responsibility. As long as the repository interface is declared in the domain, and the impl is in the infrastructure (dependency injected), is it considered bad design to pass a repository interface as an argument to a method on an entity (or other domain) class?
For example, would this be bad?
public class EntityAbc {
public void SaveTo(IEntityAbcRepository repos) {...}
public void DeleteFrom(IEntityAbcRepository repos) {...}
}
What if a particular entity needed access to other aggregate root repositories? Would this be ok or not, and why?
public void Save() {
var abcRepos = DependencyInjector.Current.GetService<IEntityAbcRepository>();
var xyzRepos = DependencyInjector.Current.GetService<IEntityXyzRepository>();
// work with repositories
}
Update 1
I did not mention moving code to an application layer because I consider some of the code that uses IEntityAbcRepository to involve business rule enforcement. The repository impl should be as vanilla as possible, right? Its main responsibility should just be a simple abstraction over the ORM, allowing you to find / add / update / delete entities. Wrong?
Also, this question applies to methods on other non-entity domain classes -- factories, services, whatever pattern may be appropriate. Point being, I'm asking the question about any method on a domain class, not just an entity class. #Eranga, this is one place where you can use constructor injection because factories & services are not part of the ORM.
The application layer could then coordinate flow by injecting a repository impl into its constructor, and passing it as an argument to a domain service or factory. Is this bad practice?
Update 2
Adding another clarification here. What if the domain only needs access to the IEntityAbcRepository in order to execute its Find() method(s)? In the example above, the SaveTo and DeleteFrom methods would not invoke any add / update / delete methods on the repository interface.
So far we've combined the find / add / update / delete methods on a single aggregate root repository interface for simplicity. But I suppose there's nothing stopping us from separating them out into 2 interfaces, like so:
IEntityAbcReadRepository <-- defines all find method signatures
IEntityAbcWriteRepository <-- defines all add / update / delete method sigs
In this case, would it be bad practice to pass IEntityAbcReadRepository as a parameter to a domain method?
Your first approach is better compared to the second approach which uses "Service Locator" pattern. Dependencies are more obvious in the first approach.
Here are some links that explains why "Service Locator" is a bad choice
Is it bad to use servicelocation instead of constructor injection
...
Singleton Vs ServiceLocator
Say no to ServiceLocator
Both of these solutions stem from the fact that EF does not allow you to use constructor injection. However you can use property injection as explained in this answer. But that does not guarantee that mandatory dependencies are present.
So your first approach is the better solution.
Short answer: Yes!
Long answer:
Consider creating an AbcService in your application service layer. This service layer sits between your domain and your infrastructure. You can inject as many repositories into AbcService as you want. Then let the service handle SaveTo and DeleteFrom.
SaveTo and DeleteFrom, unless you are saving to and deleting from another entity, i.e. no data access is involved, are methods that sound like they shouldn't be on a domain entity, IMO.
Having persistence logic in your domain entities is IMO bad design in the first place. Good separation of concerns should mean that domain/business logic is separated from persistence logic, so your domain classes should be persistence ignorant.
Previous Entity Framwork versions might not have allowed such a separation but I think most recent versions solved that problem. I'm not that familiar with EF though, so I might be wrong.
With that said, where can you put methods such as Save() and Delete() ?
If you want to add to/remove your entity from its repository, Repository.Add() and Repository.Remove() are good choices. A repository basically serves as an illusion of an in-memory collection of your entities, so it makes sense for it to behave just like a collection or a list with the appropriate methods.
If you want to persist changes made to an existing entity, there are other ways to do that. You could have a Repository.Save() method but some consider it bad practice. Oftentimes the changes are part of a higher level operation handled in a transaction-like context such as a Unit of Work, in that case you can let the operation persist all the objects in its scope when it finishes. For instance, if you use an Open Session in View approach for your web application, changes are automatically persisted when the request ends.
Or you can rely on an ad-hoc call of your ORM's Save() method for your particular entity which hopefully shouldn't be grafted onto the entity code itself (with NHibernate, for instance, it's available at runtime on the proxied entity).
[Update]
Putting that in perspective with your subsequent questions (though I'm not sure I understand all of them well) :
I see no value in splitting your repository into a ReadRepository and a WriteRepository. In DDD, a repository's responsibility is clearly to provide a collection to query from as well as add to or remove from. It's still quite cohesive that way.
It's not an entity's responsibility to fiddle with its own persistence, so it shouldn't be aware of its own repository for that precise purpose. Otherwise, it's pretty rare that an entity rightfully needs to have knowledge of its own repository (usually it means that the entity has a relationship to another entity of the same type, like parent/child, and you want to get the other entity from the repository)
However, entities and other domain objects obviously do need to obtain references to other entities at times. In that case, try to get these references through traversal of other objects within the boundary of your aggregate first before looking for a repository. If you absolutely need a repository to get the object you want, it's a good idea to inject the repository through any flavour of injection you like. As Eranga pointed out, service locator might turn out to be a sub-par dependency injection ersatz though.
Last thing, the kind of injection you mentioned - SaveTo(IEntityAbcRepository repos) - is peculiar because it is neither constructor nor setter injection, but rather an ephemeral injection lasting just the time of a method. It implies that whoever calls your method must know what repository to pass at that precise moment, which is not obvious. It might be useful, but I'd say it's not the form of injection you would typically mainly use.

Where do you put methods for common web uri paths

We have a pretty common architecture:
Database
Repository Layer
Business Objects
Services Layer - serves DTOs to the client
Web Layer (MVC)
We've got a number of common paths to resources, in particular images and podcasts (Ex. http://media.mysite.com/podcasts/). I want to create a static utility class with properties:
MySite.Utils.ImagePathUri
MySite.Utils.PodcastsPathUri
etc
My question is: Where do you put uri paths? Into which project does this utility class go?
Initially, it seemed a no-brainer: the web layer. It's a web site. I should be able to change the urls of a site without the other layers knowing about it.
Everything was fine, but, . . . then one day one of my services needed to provide a SyndicationFeed type. The SyndicationFeed needs a full URI, not just a partial file name. But the services shouldn't have access to full paths. Or should they?
I've debated with myself several things, but can't come up with a firm position:
Move the paths to the services layer. That tightly couples the web layer to the services layer, but maybe that's ok, since they're pretty tightly coupled to begin with.
Move the paths to the business objects or repos. I don't like this, but if I'm open to putting it into the services layer, I have to at least consider it.
Don't use SyndicationFeed inside of services layer, but use it only in the web layer. Solves the issue, but it seems like SyndicationFeed should belong in a services layer.
Discard SyndicationFeed. Any SyndicationFeed can more easily be created in MVC with a PartialView that generates the appropriate XML without having to mess with the bloated abstractions like ElementExtensions. I like this one, but we're using SyndicationFeed in a number of places, so that one will take the most explaining to do.
Provide a fake uri to the syndication feed in the services layer and then change it in the web layer. Can you say hack?
Put the full path in the database. That sounds ok at first, but then I realize that it breaks as soon as you have a dynamically generated image.
Some other solution that doesn't occur to me.
What are your thoughts? Where do you put utility classes for web resources (images, podcasts, etc)? And if you say "web layer", what's your take on the SyndicationFeed issue?
UPDATE
At the end of the day, I decided to scrap the SyndicationFeed class, which negated the need for including the path to the file in the service and repository layers. However, the problem still comes up elsewhere and using DI and, in particular, an IoC like Ninject makes perfect sense. So does wrapping together these into a common interface.
SyndicationFeed, View engines and why Declarative does Declarative better
I ditched the SyndicationFeed and instead created the XML that I needed using Razor. Not only is it much easier to create, but it's 1000% more readable. I've come around to the opinion that using imperative code (C#, VB, etc.) to create XML is just harder than it ought to be. XML is declarative, not imperative.
Instead, I've now decided that declarative syntax of View Engines (e.g. Razor) is much easier to work with than imperative languages.
I feel your pain. I too had a similar situation that I resolved by passing the uri to my repository layer, from my web layer.
My project uses Ninject for binding, and since I was already passing the connection string to the repository with Ninject, it was a simple matter to pass my path string as well.
My repository then massages the path string and populates the necessary properties in my business object.
Is this proper? I do not know, but it works for now. I am not completely happy with the solution, but I have not yet had a chance attempt an improvemnt.
Would love to hear how others have dealt with this.
Facing a similar situation I felt the best way to approach it was to define a configuration interface that resulted in an object at the top most layer. Each layer in between would refine the interface with more specific properties and operations:
public interface IWebConfiguration
{
string RootImageUri { get; }
}
the service would layer would add the things needed by itself:
public interface IServicesConfiguration
{
string SyndicationFeedUri { get; }
}
public interface IDatabaseConfiguration
{
string ConnectionString { get; }
}
In the end I had the web tier implement the specific object that wired up all of the interfaces. Ugly? Perhaps. I will admit there was calls to isa in there and some casting.
However, I was able to then pass to each layer a strongly typed interface. In my opinion it was better than having a series of calls to get plain old string from a config file. Also, because each property was specific to a layer and the aggregate object was being passed around I only had to load the configuration once.

ASP.NET MVC IoC usability

How often do you use IoC for controllers/DAL in real projects?
IoC allows to abstract application from concrete implementation with additional layer of interfaces that should be implemented. But how often concrete implementation changes? Should we really have to do job twice adding method to interface then the implementation if implementation hardly will ever be changed? I took part in about 10 asp.net projects and DAL (ORM-like and not) was never rewritten completely.
Watching lots of videos I clearly understand that IoC "is cool" and the really nice way to program, but does it really needed?
Added a bit later:
Yes, IoC allows prepare better testing environment, but we also have nice way to test DAL without IoC. We wrap DAL calls to database into uncommited transactions without risk to make data unstable.
IoC isn't a pattern only for writing modular programs; it also allows for easier testing, by being able to swap in mock objects that implement the same interface as the components they stand in for.
Plus, it actually makes code much easier to maintain down the road.
It's not IOC that allows you to abstract application from concrete implementation with additional layer of interfaces, this is how you should design your application in order to be more modular and reusable. Another important benefit is that once you've designed your application this way it will be much easier to test the different parts in isolation without depending on concrete database access for example.
There's much more about IoC except ability to change implementation:
testing
explicit dependencies - not hidden inside private DataContext
automatic instantiation - you declare in constructor that you need something, and you get it - with all deep nested dependencies resolved
separation of assemblies - take a look at S#arp Architecture to see how IoC allows to avoid referencing NHibernate and other specific assemblies, which otherwise you'll have to reference
management of lifetime - ability to specify per request / singleton / transitive lifetime of objects and change it in one place, instead of in dozens of controllers
ability to do dynamic stuff, like, getting correct data context in model binders, because with IoC you now have metadata about your dependencies; and this shows that maybe IoC does to your object dependencies what reflection does to C# programming - a lot of new possibilities, that you never even thought about
And so on, I'm sure I missed a lot of positive stuff. While the only "bad" thing that I can think about (and that you mentioned) is duplication of interface, which is non-issue with modern IDEs support for refactoring.
Well, if your data interfaces change every day, and you have hundreds of them - you may want to avoid IoC.
But, do you avoid good design practices just because it's harder to follow them? Do you copy and paste code instead of extracting a method/class, just because it takes more time and more code to do so? Do you place business logic in views just because it's harder to create view models and sync them with domain models? If yes, then you can avoid IoC, no problem.
You're arguing that using IOC takes MORE code than not using it. I disagree.
Here is the entire DAL IOC configuration for one of my projects using LinqToSql. The ContextProvider class is simply a thread safe LinqToSql context factory.
container.Register(Component.For<IContextProvider<LSDataContext>, IContextProvider>().LifeStyle.PerWebRequest.ImplementedBy<ContextProvider<LSDataContext>>();
container.Register(Component.For<IContextProvider<WorkSheetDataContext>, IContextProvider>().LifeStyle.PerWebRequest.ImplementedBy<ContextProvider<WorkSheetDataContext>>();
container.Register(Component.For<IContextProvider<OffersReadContext>, IContextProvider>().LifeStyle.PerWebRequest.ImplementedBy<ContextProvider<OffersReadContext>>();
Here is the entire DAL configuration for one of my projects using NHibernate and the repository pattern:
container.Register(Component.For<NHSessionBuilder>().LifeStyle.Singleton);
container.Register(Component.For(typeof(IRepository<>)).ImplementedBy(typeof(NHRepositoryBase<>)));
Here is how I consume the DAL in my BLL (w/ dependency injection):
public class ClientService
{
private readonly IRepository<Client> _Clients;
public ClientService(IRepository<Client> clients)
{
_Clients = clients;
}
public IEnumerable<Client> GetClientsWithGoodCredit()
{
return _Clients.Where(c => c.HasGoodCredit);
}
}
Note that my IRepository<> interface inherits IQueryable<> so this code is very trivial!
Here's how I can test my BLL without connecting to a DB:
public void GetClientsWithGoodCredit_ReturnsClientWithGoodCredit()
{
var clientWithGoodCredit = new Client() {HasGoodCredit = true};
var clientWithBadCredit = new Client() {HasGoodCredit = false};
var clients = new List<Client>() { clientWithGoodCredit, clientWithBadCredit }.ToTestRepository();
var service = new ClientService(clients);
var clientsWithGoodCredit = service.GetClientsWithGoodCredit();
Assert(clientsWithGoodCredit.Count() == 1);
Assert(clientsWithGoodCredit.First() == clientWithGoodCredit);
}
ToTestRepository() is an extension method that returns a fake IRepository<> that uses an in-memory list.
There is no possible way you can argue that this is more complicated than newing up your DAL all over your BLL.
The only way you could have ever written the above test is by connecting to a DB, saving some test clients, and then querying. I guarantee that takes 100+ times longer to execute than this did. (Times that by 1000 tests and you can go get some coffee while you're waiting.)
Also, by using uncommitted transactions for testing you introduce debugging nightmares resulting from ORMs that don't query over uncommitted entities.

Repository Pattern vs DAL

Are they the same thing? Just finished to watch Rob Connery's Storefront tutorial and they seem to be similar techinques. I mean, when I implement a DAL object I have the GetStuff, Add/Delete etc methods and I always write the interface first so that I can switch db later.
Am I confusing things?
You're definitely not the one who confuses things. :-)
I think the answer to the question depends on how much of a purist you want to be.
If you want a strict DDD point of view, that will take you down one path. If you look at the repository as a pattern that has helped us standardize the interface of the layer that separates between the services and the database it will take you down another.
The repository from my perspective is just a clearly specified layer of access to data.Or in other words a standardized way to implement your Data Access Layer. There are some differences between different repository implementations, but the concept is the same.
Some people will put more DDD constraints on the repository while others will use the repository as a convenient mediator between the database and the service layer. A repository like a DAL isolates the service layer from data access specifics.
One implementation issue that seems to make them different, is that a repository is often created with methods that take a specification. The repository will return data that satisfies that specification. Most traditional DALs that I have seen, will have a larger set of methods where the method will take any number of parameters. While this may sound like a small difference, it is a big issue when you enter the realms of Linq and Expressions.
Our default repository interface looks like this:
public interface IRepository : IDisposable
{
T[] GetAll<T>();
T[] GetAll<T>(Expression<Func<T, bool>> filter);
T GetSingle<T>(Expression<Func<T, bool>> filter);
T GetSingle<T>(Expression<Func<T, bool>> filter, List<Expression<Func<T, object>>> subSelectors);
void Delete<T>(T entity);
void Add<T>(T entity);
int SaveChanges();
DbTransaction BeginTransaction();
}
Is this a DAL or a repository? In this case I guess its both.
Kim
A repository is a pattern that can be applied in many different ways, while the data access layer has a very clear responsibility: the DAL must know how to connect to your data storage to perform CRUD operations.
A repository can be a DAL, but it can also sit in front of the DAL and act as a bridge between the business object layer and the data layer. Which implementation is used is going to vary from project to project.
One large difference is that a DAO is a generic way to deal with persistence for any entity in your domain. A repository on the other hand only deals with aggregate roots.
I was looking for an answer to a similar question and agree with the two highest-ranked answers. Trying to clarify this for myself, I found that if Specifications, which go hand-in-hand with the Repository pattern, are implemented as first-class members of the domain model, then I can
reuse Specification definitions with different parameters,
manipulate existing Specification instances' parameters (e.g. to specialize),
combine them,
perform business logic on them without ever having to do any database access,
and, of course, unit-test them independent of actual Repository implementations.
I may even go so far and state that unless the Repository pattern is used together with the Specification pattern, it's not really "Repository," but a DAL. A contrived example in pseudo-code:
specification100 = new AccountHasMoreOrdersThan(100)
specification200 = new AccountHasMoreOrdersThan(200)
assert that specification200.isSpecialCaseOf(specification100)
specificationAge = new AccountIsOlderThan('2000-01-01')
combinedSpec = new CompositeSpecification(
SpecificationOperator.And, specification200, specificationAge)
for each account in Repository<Account>.GetAllSatisfying(combinedSpec)
assert that account.Created < '2000-01-01'
assert that account.Orders.Count > 200
See Fowler's Specification Essay for details (that's what I based the above on).
A DAL would have specialized methods like
IoCManager.InstanceFor<IAccountDAO>()
.GetAccountsWithAtLeastOrdersAndCreatedBefore(200, '2000-01-01')
You can see how this can quickly become cumbersome, especially since you have to define each of the DAL/DAO interfaces with this approach and implement the DAL query method.
In .NET, LINQ queries can be one way to implement specifications, but combining Specification (expressions) may not be as smooth as with a home-grown solution. Some ideas for that are described in this SO Question.
My personal opinion is that it is all about mapping, see: http://www.martinfowler.com/eaaCatalog/repository.html. So the output/input from the repository are domain objects, which on the DAL could be anything. For me that is an important addition/restriction, as you can add a repository implementation for a database/service/whatever with a different layout, and you have a clear place to concentrate on doing the mapping. If you were not to use that restriction and have the mapping elsewhere, then having different ways to represent data can impact the code in places it shouldn't be changing.
It's all about interpretation and context. They can be very similar or indeed very different, but as long as the solution does the job, what is in a name!
In the external world (i.e. client code) repository is same as DAL, except:
(1) it's insert/update/delete methods is restricted to have the data container object as the parameter.
(2) for read operation it may take simple specification like a DAL (for instance GetByPK) or advanced specification.
Internally it works with a Data Mapper Layer (for instance entity framework context etc) to perform the actual CRUD operation.
What Repository pattern doesn't mean:-
Also, I've seen people often get confused to have a separate Save method as the repository pattern sample implementation besides the Insert/Update/Delete methods which commits all the in-memory changes performed by insert/update/delete methods to database. We can have a Save method definitely in a repository, but that is not the responsibility of repository to isolate in-memory CUD (Create, Update, Delete) and persistence methods (that performs the actual write/change operation in database), but the responsibility of Unit Of Work pattern.
Hope this helps!
Repository is a pattern, this is a way to implement the things in standardized way to reuse the code as we can.
Advantage of using repository pattern is to mock your data access layer, so that you can test your business layer code without calling DAL code. There are other big advantages but this seems to be very vital to me.
From what I understand they can mean basically the same thing - but the naming varies based on context.
For example, you might have a Dal/Dao class that implements an IRepository interface.
Dal/Dao is a data layer term; the higher tiers of your application think in terms of Repositories.
So in most of the (simple) cases DAO is an implementation of Repository?
As far as I understand,it seems that DAO deals precisely with db access (CRUD - No selects though?!) while Repository allows you to abstract the whole data access,perhaps being a facade for multiple DAO (maybe different data sources).
Am I on the right path?
One could argue that a "repository" is a specific class and a "DAL" is the entire layer consisting of the repositories, DTOs, utility classes, and anything else that is required.

Resources