Property Injection Issue

Sep 20, 2011 at 12:59 PM

Hi

I am using Unity to implement the Repository pattern. In my Service class I have an instance of the Repository as a property.

 

public class CustomerService{

[Dependency]

public ICustomerRepository CustomerRepo {get;set;}

}

 

I then use the UnityContainer to resolve the CustomerService type and the ICustomerRepository is resolved as well.  

The issue is that inside the CustomerReposotory which implements the ICustomerRepository interface, I have another dependency property. Lets say Its my ILogWriter object that carries out the logging. The registerations are all in the container that resolved the CustomerService however it does not seem to be instantiating the ILogWriter.

Does Unity only work with the top level objects and their public dependency properties?

 

CustomerService=>ICustomerRepository  (Resolved OK)

CustomerService=>ICustomerRepository=>ILogWriter (Throws a NullReferenceException)

 

My current work around is to have another Factory class that is used by the Repositories to resolve types inside them.

 

Am I missing something?

Sep 20, 2011 at 1:05 PM

I changed ILogWriter from PropertyInjection to Constructor Injection and it works fine.

 

So my CustomerRepository constrcutor is

 

public CustomerRepository(ILogWriter logWriter)

{

this.logWriter = logWriter;

}

 

The logWriter parameter is resolved ok (so the mapping is there) but having it as below does not work.

 

public class CustomerRepository:ICustomerRepository

{

[Dependency]

public ILogWriter LogWriter{get;set;}

}

Sep 21, 2011 at 8:17 AM

Hi,

Have you also registered a type mapping for the ILogWriter?

 

Noel Angelo Bolasoc
Avanade Software
Avanade, Inc.
Contact Us

 

 

Sep 21, 2011 at 1:09 PM

Hi Noel,

 

Thanks for replying, the ILogWriter works if i pass it through the constructor injection and then set the this.LogWriter property to the constructor parameter. So the type mapping is definatly registered. I am now using constructor injection but it means that if my class has dependancies on other repositories then I will have to instantiate them using the constructor parameters which may get messy if the number of parameter which need to be passed become large.

 

Sep 22, 2011 at 9:42 AM

Can you also post how did you register and resolve your types? I'm not sure but maybe you must be missing something.

 

Noel Angelo Bolasoc
Avanade Software
Avanade, Inc.
Contact Us

 

Sep 22, 2011 at 10:38 AM

I think, I know what the issue is as I have the property injection working fine in another repository. I was trying to call the property inside my constructor and it looks like the Unity calls the constructor first and then injects the properties. 

So, I am assuming that if the injected properties need to be used in the constructor then they need to be set using the constructor injection method.  Any methods of a class can use the injected property normally.

Thanks Noel for your help.