Removing objects using dependency injection

I created a repository class that I want to use in the code behind the page. I am using constructor injection in code by page to create an instance of 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 by 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(); } 

That's where I got a little confused. How to ensure proper storage location? For example, I cannot wrap repository calls with statements in code per page, thereby using the dispose method in the repository.

+4
source share
2 answers

You must use the "Register to allow release" template.

In particular, you must remember that it always releases what you allow . It is the composer's responsibility to keep track of whether a dependency should be chosen. This is not trivial as it depends on various factors:

  • Is dependency implementation IDisposable?
  • Does the dependency lifetime indicate that it should be located now or later?

This is such a difficult task that you must use the appropriate DI container for the job.

However, keep in mind that this ultimately depends on whether your container supports a DI container from decommissioning. For example, Castle Windsor does, while StructureMap does.

+4
source

Well, the idea is that everything that is created by the DI container is deleted if it is IDisposable . The only problem is when this happens. I suspect that there may be differences between the various containers, but I take it upon myself to implement Dispose() on the created object and explicitly call Dispose() on the object that was entered.

+1
source

Source: https://habr.com/ru/post/1334055/


All Articles