I have created a repository class that I want to use in a code behind page. I’m using constructor injection in the code behind page to instantiate the repository.
Repository class:
BritanniaPremierEntities PBEntities = new BritanniaPremierEntities();
public IQueryable<TradeRoutes> GetRoutes()
{
var routes = PBEntities.TradeRoutes.OrderBy(c => c.ConsignmentDate);
return routes;
}
public IQueryable<TradeRoutes> GetExpiredRoutes()
{
var routes = PBEntities.TradeRoutes.Where(
c => c.ConsignmentDate <= System.DateTime.Now);
return routes;
}
Code behind page
private IRepository repos;
public Admin_TradeRoutesAdmin()
: this(new Repository())
{
}
public Admin_TradeRoutesAdmin(IRepository repos)
{
this.repos = repos;
}
public IQueryable GetTradeRoutes()
{
// call repository method
return repos.GetRoutes();
}
Here is where I get a little confused. How should I ensure the repository is disposed correctly? For instance, I’m unable to wrap the repository calls in using statements in the code behind page, thus making use of the dispose method in the repository.
You should employ the Register Resolve Release pattern.
Specifically you should remember to always Release what you Resolve. It’s the responsibility of the Composer to keep track of whether or not the dependency should be disposed. This is not trivial as it depends on different factors:
This is such a complex task that you should use a proper DI Container for the job.
However, keep in mind that this ultimately depends on whether or not your DI Container supports decommissioning. For example, Castle Windsor does while StructureMap doesn’t.