Using Property Injection?

Topics: Prism v2 - Silverlight 3
Oct 15, 2009 at 2:02 PM

I'm a beginning Prism user and I am attempting to use property injection to instantiate a service I have written.  I am registering the service in the bootstrapper (I want my service to be available to multiple modules) as follows:

 protected override void ConfigureContainer()

{

   Container.RegisterType<IMyService, MyService>(new ContainerControlledLifetimeManager());

}

In my ViewModel then I have added a public property as follows:

[Dependency]

public IMyService MyService { get; set;}

Now when I try to call a method on the service in my ViewModel as follows:

MyService.Start()

I get the standard error "Object reference not set to an instance of an object"...debugging shows MyService is null.

Could someone please explain what I am missing?  From reading the Unity documentation, my understanding is that using the [Dependency] attribute will cause an instance of MyService to be created and set as the value of the MyService property automatically.

Do I still need to resolve the service as follows:

Container.Resolve<IMyService>();

and if I still need to do this where do I do it?  In the ViewModel constructor?  The corresponding Module?

 

Oct 15, 2009 at 8:47 PM

Hi

When you are using Unity Property Injection you have to take in account the following things:

  • You cannot access the injected property from the constructor of the class, at this time the property hasn't been instantiated. For further information visit this site. If you require access from the constructor to the injected object use constructor injection.
  • You must create a new instance of your class by using Container.Resolve<YourViewModel> in order to resolve all the dependencies injections in the class. For further information visit this site, section: Resolving References to Objects

I hope this answer helps you

Fernando Antivero
http://blogs.southworks.net/fantivero