This is related to question posted here. My Core project has following .
public interface IRepository<T> : IDisposable
{
IQueryable<T> All { get; }
IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties);
TEntity Find(int id);
void InsertOrUpdate(T entity);
void Delete(int id);
void Save();
}
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
DAL has CustomerContext and CustomerRepository. This project depends upon Entity Framework.
public class CustomerContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
}
public class CustomerRepository : IRepository<Customer>
{
}
Next comes my BAL. This is a class library project. I need to perform some actions on customer repository but I want to do it without adding dependency on DAL directly. I am trying to do via DI using ninject. I am setting up binding between IRepository and CustomerRepository as follows.
var Kernel = new StandardKernel();
Kernel.Bind<IRepository>().To<CustomerRepository>();
Let' say I have a UI application that will call some API from BAL. Where exactly above code for binding IRepository to CustomerRepository should be placed? Is there any way of doing this binding via App.config?
As you can see if I put this somewhere in BAL, then I will have to add a reference to DAL project because I am using CustomerRepository which is defined in DAL layer.
You never set up your container in a low level layer. Rather, you have a composition root somewhere up the hierarchy. In case of a desktop application, the
Main
is a good candidate. In a web application it would be theGlobal.asax
'sApplication_Start
.First of all: Do not use generic repositories which expose
IQueryable<TEntity>
.Your questions:
Why can't you add a dependency to your DAL from your UI project? It will also simplify the installation since the DAL will automatically be included when you publish the project and/or create a setup package.
Don't create a reference or configuration in the BAL. It's the UI project which is the root. So any configuration should be added into it.
I usually create a composition root in every project and then invoke the root in every assembly from my startup project. That means that the startup project only has to know which projects we got, but not what they contain.