Get service from RootWorkItem or Inject to constructor

Aug 14, 2009 at 10:02 AM

Hi,

Consider the following project setup. Project has 3 subprojects: Common services, Business Specific services and Shell for presenting. In Business project I want to use service from Common project. Is it better to get this service from RootWorkItem, as follows:

 

private IConfigurationService ConfigurationService { get; set; }

public MonitorService()

{ ConfigurationService = RootWorkItem.Get<IConfigurationService>(); }

 

or inject it: 

private IConfigurationService ConfigurationService { get; set; }

public MonitorService([ServiceDependency]IConfigurationService configService)

{ ConfigurationService = configService; }

 

what are the pros and cons for these methods?

Coordinator
Aug 14, 2009 at 3:31 PM

An excellent question.  I will typically opt for an auto-injected mechanims when I can (like your second example), and I'd say neitehr is more or less "correct", it's purely a matter of personal preference and style.

There is also a third way as well:

[ServiceDependency]
private IConfigurationService ConfigurationService { get; set; }

public MonitorService(IConfigurationService configService) { }
THis one is *almost* the same, but does have one drawback.  The IoC Framework cannot set the ConfigurationService property until after the object has been constructed, so if you need to use the service in the object constructor, this method will fail (as it will be null until it gets injected post-construction).
Aug 14, 2009 at 5:24 PM

very explanatory, thanks!