如何在深层次的类中使用单例对象

问题描述 投票:0回答:1

您好我有以下问题。

ConfigureServices类的Startup方法中,我有一个只有一次构造的对象。 必须在层次结构的深层传递此对象才有用。我不想将对象从对象传递给对象。

如果我在服务集合中添加它我什么也解决,因为我深入其他服务,其组件需要它。

 public void ConfigureServices(IServiceCollection services)
    {
           var dependencyObject=await Database(....get me something...);
           var singleton=new Singleton(dependencyObject);

           var userService=new SomeService(complexObject); //transient !
           services.AddTransient(userService);
    }

    public class SomeService
    {
       public SomeComponentOfService component{get;set;}
       SomeService(Singleton singleton)
       {
         component=new  SomeComponentOfService(singleton);
       }
    }

public class SomeComponentOfService
{
   public Singleton singleton;
   public SomeComponentOfService(Singleton single)
   {
      ......on and on....
    }
}

这个列表继续与Singleton对象....

现在您可以看到我的Transient服务需要一个依赖于另一个服务(数据库)的单例对象。因此,必须在层次结构的高处创建单例。

问题是我的SomeService必须传递到其他对象这个singleton,并且有一个巨大的等级。

我可以以某种方式创建我的Singleton高链,并从我的服务集合(无论我需要它)获得它?

oop asp.net-core dependency-injection singleton
1个回答
1
投票

在要使用Singleton对象的类中创建一个静态变量。自己新建Singleton或让依赖注入框架执行它。然后将其添加到该类中的静态变量。

一些依赖注入框架也有参数注入。如果它是深层次类的源,您可以通过参数注入添加依赖项注入框架。

© www.soinside.com 2019 - 2024. All rights reserved.