您好我有以下问题。
在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
高链,并从我的服务集合(无论我需要它)获得它?
在要使用Singleton对象的类中创建一个静态变量。自己新建Singleton或让依赖注入框架执行它。然后将其添加到该类中的静态变量。
一些依赖注入框架也有参数注入。如果它是深层次类的源,您可以通过参数注入添加依赖项注入框架。