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.