0

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.

Tim
  • 459
  • 1
  • 4
  • 20
  • 1
    If it is transient, it will be a new one. That is what transient means. Have you considered making it scoped instead? – mjwills Feb 22 '19 at 12:28
  • 2
    Use `AddScoped`, don't use singleton for database contexts or you can run into thread synchronization issues. Here's a great [answer](https://stackoverflow.com/a/38139500/5062791) describing the difference between Transient, Scoped & Singleton. – ColinM Feb 22 '19 at 12:29

1 Answers1

1

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.

ColinM
  • 2,622
  • 17
  • 29
keyle56
  • 123
  • 6