开发者

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 obj开发者_开发技巧ects 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 ?


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);
  }
}


I didn't really understood your question. But it seems you are looking for Service Locator pattern. Most IoC frameworks have some kind of static object, that allows you to create dependencies on-the-fly instead of injecting them into constructors or properties.

But this has requirement, that your code knows about your IoC. I hate this requirement, so its not the possible solution. In this case, creating Factory, that allows you to create your dependencies for you is better solution. In this case, concrete way those dependencies are resolved can be hidden by concrete factory, that is internaly using your specific IoC.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜