简体   繁体   English

具有相关瞬态的ASP.NET Core DI

[英]ASP.NET Core DI with dependent transients

I have 2 services: IDbStorage for database operations and IExceptionManager exception management. 我有2个服务:用于数据库操作的IDbStorage和IExceptionManager异常管理。 ExceptionManager class itself relies on instance of IDbStorage: ExceptionManager类本身依赖于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. 在所有控制器中,我都使用了这两种服务。 Fe: 铁:

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? 一切正常,但是我不确定是否将同一IDbStorage实例注入CurrentExceptionMgr或创建新实例?

Thanks. 谢谢。

For .NET Core DI, there are three different service lifetimes. 对于.NET Core DI,存在三种不同的服务寿命。 You've declared IDbStorage as transient and therefore will create a new instance of OracleDbStorage every time the service is requested. 您已将IDbStorage声明为临时的,因此每次请求服务时都会创建一个OracleDbStorage的新实例。 Here is the relevant bit from .NET Core docs on this: 这是.NET Core文档中的相关内容:

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). 单例生命周期服务是在首次请求它们时创建的(或者在运行ConfigureServices并使用服务注册指定实例时创建)。 Every subsequent request uses the same instance. 每个后续请求都使用相同的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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