Don't create any Repository
objects in your business layer. You should use a unit of work pattern together with your repository pattern. Your DAL should have a unit of work class that exposes only the necessary repositories as properties. This unit of work class acts as the only gateway between your business layer and data access layer.
For example, let's say I have two entities Foo
and Bar
structured like this:
public class Foo
{
public int FooId { get; set; }
public virtual ICollection<Bar> Bars { get; set; }
}
public class Bar
{
public int BarId { get; set; }
public int FooId { get; set; }
public virtual Foo Foo { get; set; }
}
My UnitOfWork
class might look like this:
public class UnitOfWork
{
private Repository<Foo> foos;
public Repository<Foo> Foos
{
get
{
if(foos == null)
foos = new Repository<Foo>();
return foos;
}
}
...
}
As far as defining a repository for every entity, you need to decide which ones you really need to include. For example my UnitOfWork
doesn't include a Repository<Bar>
. Perhaps I did this because I can get to all of the Bar
s through the linked property on their associated Foo
and it doesn't make sense in my domain to look up a Bar
on it's own. Bottom line: it all depends on your domain which repositories you expose. Just choose wisely.
This article was written by the ASP.NET/MVC team but the repository/unit of work principles in it are good practices for anything using Entity Framework. It's a good read whether you are working with MVC or not.