开发者

Object disposal with dependency injection

开发者 https://www.devze.com 2023-02-01 23:20 出处:网络
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.

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_TradeRoutesAdm开发者_StackOverflow社区in(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:

  • Does the dependency implement IDisposable?
  • Does the dependency's lifetime indicate that it should be disposed now or later?

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.


Well, the idea generally is that whatever gets created by a DI container gets disposed, provided it is an IDisposable. The only issue is when that happens. I suspect there might be differences between different containers, but my take on this would be to implement Dispose() in the object being created, and explicitly calling Dispose() on the object being injected.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号