Can the following Microsoft document help?
Dependency injection in ASP.NET Core
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-6.0
See "Disposal of services" section.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I have a class that implements an interface and also IDisposable
:
public interface IMyObject : IDisposable
{
void MyMethod();
}
public class MyObject: IMyObject
{
public void MyMethod()
{
//...
}
}
Then I inject this interface, let's say in a Controller:
private IMyObject _myObject;
public MyController(IMyObject myObject)
{
_myObject = myObject;
}
Then I want to use that class somewhere in the Controller, but I am undecided about the object being disposed properly.
So far I've always wrapped it inside a using
statement like:
public void MyAction()
{
using var myObject = new MyObject();
myObject.MyMethod();
}
This ensures that it's disposed safely.
I was wondering if using the injected object would be exactly the same, or if it could happen that it's not disposed properly?
public void MyAction()
{
_myObject.MyMethod();
}
Can the following Microsoft document help?
Dependency injection in ASP.NET Core
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-6.0
See "Disposal of services" section.