I am building a Prism 4 app, and I use the ServiceLocator
to instantiate objects. The ServiceLocator
is causing unit testing problems, and that leads me to wonder whether I should go back to injecting the IoC container into each class that needs it.
Here is an example of the problem from a repository base class:
protected RepositoryBase(string filePath, Type contextType, string edmName)
{
m_Logger = ServiceLocator.Current.GetInstance<ILoggerFacade>();
// Log invocation
m_Logger.Log("RepositoryBase constructor invoked.", Category.Info, Priority.None);
// Create object context
...
// Log completion
m_Logger.Log("RepositoryBase constructor completed.", Category.Info, Priority.None);
}
I am creating unit tests for my repository, and I have discovered that the ServiceLocator
doesn't work, presumably because Prism isn't initialized for my test.
Can the ServiceLocator
be used in a testing context? Sould I drop it and go back to injecting the IoC container directly? Since service locators seem to be falling out of favor generally, would I be better off not using it? Thanks for your help.
You need to create a mock IServiceLocator, initialize the service locator with your mock provider in your test.
That should do it.