简体   繁体   中英

How does the GC works with DI in .Net Core 2

Usually when using entity framework I'm using a "using" clause:

using (var db = new dbcontext())
{
    var blabla = db.table.tolist();
}

Now, we have migrated our platform into .Net Core (2) and since there is a great DI mechanism we have decided to use it. Now, instead of using the above way, now we are getting the dbcontext as a parameter in the constructor:

public MeaningfullNameController(dbcontext db)
{
    this.db = db;
}

And when another class needs to use the dbcontext we just pass the above dbcontext in the constructor of the second class.

public class NewClass(dbcontext db)
{
    this.db = db;
}

This situation got me thinking, how does the garbage collector handle this situation? Is there a difference from the first approach in terms of performance? memory leaks? etc.

Thanks, Shaul

There is definitely a difference in terms of lifecycle.

In the first approach, you create the object (and allocate memory, and any other resources it needs) via new . The end of the using block will call Dispose on it, freeing any non-memory resources. When the object goes out of scope, the GC can see it is not being used and reclaim it at any time.

In the DI approach, the lifecycle is being managed by the DI-framework. The DI-framework will allocate it and Dispose it. The DI-framework may allocate it once for the entire lifetime of the application, once per invocation of the DI-supporting-method or anything in between. Thus, the lifetime is probably longer and might be substantially longer. If the object lives for a longer time, that means the .NET Core runtime system has allocate it less often and reclaim it less often. It does less work. But it means the objects resources stay used for longer: a connection to the database and any handles will be kept around longer. If you are not using the db only once, for example, during the lifetime of the application and you keep it active for the entire lifetime, you are just wasting resources that you dont need.

In other words, there isn't a simple answer. For resources that are being used frequently, using DI with a lifecycle of per-method-call compared to explicitly calling new + Dispose will involve similar amounts of work. For other types of uses, it will depend on what you are doing and what will "better" for your use case.

In general though, this isn't something you should try and optimize for, unless you know this is causing performance issues. Optimize for the developer first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM