Reputation: 9360
Hello i have the following problem.
I have an object that gets constructed only once more specifically, in the ConfigureServices
method of the Startup
class.
This object has to be passed deep in the hierarchy to be useful.I do not want to pass from object to object a reference to this object.
If i add it in the collection of services i solve nothing since i use it deep inside another service,whose components need it.
Example
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....
}
}
And the list goes on and on with the Singleton
object....
Now as you can see my Transient
service needs a singleton object that depends on another service (Database).So the singleton has to be created high up the hierarchy.
The problem is that my SomeService
has to pass down to other objects this singleton
,and there's a giant hierarchy.
Can i somehow create my Singleton
high up the chain and get it from my collection of services (wherever i need it ) ?
Upvotes: 0
Views: 52
Reputation: 1273
Make a static variable in the class you want to use the Singleton object in. New up the Singleton yourself or have the dependency injection framework do it. Then adding it to the static variable in that class.
Some dependency injection frameworks also have parameter injection. You may be able to let the dependency injection framework adding by parameter injection if it is the source of your deep down class.
Upvotes: 1