Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can objects be injected in run time (after the initialization)?

I'm using the Dependency Injection technique in my two current ongoing projects.

I use Unity as my IoC framework.

I'm using a class called ComponentBuilder which is in charge of creating the application objects and their events subscription as part of the initialization of the application.

Once the application is running all the objects are ready and data is passed from one object to the other.

The problem i have is:

Some of the objects are created dynamically after the initialization, these objects need other objects that already exists.

Since the ComponentBuilder already finished its part, i need to find a way of passing the needed objects to these "dynamic" objects. These dynamic objects are actually a hierarchy of objects created in run time, the deepest object in the hierarchy needs a component (object) from the top of the hierarchy.

I thought of two possible solutions (i don't like them both):

  1. Pass the container of all objects from the ComponentBuilder to the dynamic objects so that they can use and subscribe to the desired objects. the main con of this option is the expose of all objects which can hide dependencies between objects. I saw that some people pass the object container to all objects as if it were a logger or display, i think this is wrong and hides the dependencies we want to expose to other objects.

  2. Pass the needed objects to first object that is created in init time, so that later it would pass the objects down the object hierarchy to the dynamic object. the main con of this option is that some of the objects down the hierarchy don't need these objects.

can you think of a better solution ?

like image 241
Adiel Yaacov Avatar asked Oct 12 '22 09:10

Adiel Yaacov


1 Answers

Seems you need a standard factory/abstract factory pattern, where you pass in compile time dependencies in the constructor and runtime dependencies in the creation methods.

class Factory
{
  ISomeService service;

  public Factory(ISomeService service)
  {
    this.service = service;
  }


  public SomeObject CreateItem(object runtimeDependency)
  {
    return new SomeObject(service, runtimeDependency);
  }
}
like image 99
Marcus Avatar answered Oct 15 '22 09:10

Marcus