Dependency Resolution After Construction (Unity)?

Topics: Prism v4 - WPF 4
Jul 27, 2011 at 6:41 PM

I have a host application which has a dependency on a particular object, say of type IMyInterface. The concrete implementation of IMyInterface can either be null (i.e. optional dependency), or it can be provided by an external module. In this specific case, the external module (Prism IModule derived) is what provides the concrete implementation. The problem I am having is as follows. The host application's object, call it MyHostAppObject, that has this optional dependency on IMyInterface is created before the the external module is initialized. Then, when the external module registers its concrete implementation of IMyInterface with the container, MyHostAppObject does not know about it. What is a good way to handle this?

Quick code to illustrate the issue:

public class MyModule : IModule
{
  ...
  public void Initialize()
  {
    Container.RegisterType<IMyInterface, MyInterface>();
  }
}

// in host app... this object is created first
public class MyHostAppObject
{
 public
MyHostAppObject(IMyInterface obj) { } }

Developer
Jul 28, 2011 at 2:49 PM
Edited Jul 28, 2011 at 2:53 PM

Hi,

You could make your additional module publish an event with the Event Aggregator once it has registered its component in the Unity Container, and you could make your MyHostAppObject class subscribe to that event and resolve that dependency through the Unity container in the handler for that event.

I hope you find this helpful.

Guido Leandro Maliandi
http://blogs.southworks.net/gmaliandi

Jul 28, 2011 at 5:03 PM

Thank you for the response.

Is there anything wrong with initializing the modules before initializing the shell?

Developer
Jul 28, 2011 at 5:15 PM

Usually modules contain the logic to add views to regions (that are usually defined in the shell). Therefore, you wouldn't be able to add views to regions using the View Injection approach if you altered the initialization sequence.

Considering that, unless it is unavoidable, you should stick with the default initialization sequence.

I hope you find this helpful.

Guido Leandro Maliandi
http://blogs.southworks.net/gmaliandi