Reputation: 459
I have 2 services: IDbStorage for database operations and IExceptionManager exception management. ExceptionManager class itself relies on instance of IDbStorage:
public class ExceptionManager : IExceptionManager
{
private IDbStorage _CurrentDbStorage;
public IDbStorage CurrentDbStorage
{
get { return _CurrentDbStorage; }
}
public ExceptionManager(IDbStorage currentDbStorage)
{
_CurrentDbStorage = currentDbStorage;
}
}
In Startup, I declare:
services.AddTransient<IDbStorage, OracleDbStorage>();
services.AddTransient<IExceptionManager, ExceptionManager>();
In all controllers I used both Services. F.e:
public abstract class BusinessObjectManagementController<T1> : ControllerBase where T1 : BusinessObject
{
private IDbStorage _CurrentDbStorage;
public IDbStorage CurrentDbStorage
{
get { return _CurrentDbStorage; }
}
private IExceptionManager _CurrentExceptionMgr;
public IExceptionManager CurrentExceptionMgr
{
get { return _CurrentExceptionMgr; }
}
public BusinessObjectManagementController(IDbStorage currentDbStorage, IExceptionManager currentExceptionMgr)
{
_CurrentDbStorage = currentDbStorage;
_CurrentExceptionMgr = currentExceptionMgr;
}
}
Everything works fine, however I am not sure if the same instance of IDbStorage is injected to CurrentExceptionMgr or new one created?
Thanks.
Upvotes: 0
Views: 207
Reputation: 123
For .NET Core DI, there are three different service lifetimes. You've declared IDbStorage
as transient and therefore will create a new instance of OracleDbStorage
every time the service is requested. Here is the relevant bit from .NET Core docs on this:
Transient lifetime services are created each time they're requested. This lifetime works best for lightweight, stateless services.
Scoped lifetime services are created once per request.
Singleton lifetime services are created the first time they're requested (or when ConfigureServices is run and an instance is specified with the service registration). Every subsequent request uses the same instance.
Upvotes: 1