ServiceLocator not initialized in Tests project
- by Carl Bussema
When attempting to write a test related to my new Tasks (MVC3, S#arp 2.0), I get this error when I try to run the test:
MyProject.Tests.MyProject.Tasks.CategoryTasksTests.CanConfirmDeleteReadiness:
SetUp : System.NullReferenceException
: ServiceLocator has not been
initialized; I was trying to retrieve
SharpArch.NHibernate.ISessionFactoryKeyProvider
---- System.NullReferenceException : Object reference not set to an
instance of an object.
at
SharpArch.Domain.SafeServiceLocator1.GetService()
at
SharpArch.NHibernate.SessionFactoryKeyHelper.GetKeyFrom(Object
anObject) at
SharpArch.NHibernate.NHibernateRepositoryWithTypedId2.get_Session()
at
SharpArch.NHibernate.NHibernateRepositoryWithTypedId2.Save(T
entity) at
MyProject.Tests.MyProject.Tasks.CategoryTasksTests.Setup()
in
C:\code\MyProject\Solutions\MyProject.Tests\MyProject.Tasks\CategoryTasksTests.cs:line
36
--NullReferenceException at Microsoft.Practices.ServiceLocation.ServiceLocator.get_Current()
at
SharpArch.Domain.SafeServiceLocator1.GetService()
Other tests which do not involve the new class (e.g., generate/confirm database mappings) run correctly.
My ServiceLocatorInitializer is as follows
public class ServiceLocatorInitializer
{
public static void Init()
{
IWindsorContainer container = new WindsorContainer();
container.Register(
Component
.For(typeof(DefaultSessionFactoryKeyProvider))
.ImplementedBy(typeof(DefaultSessionFactoryKeyProvider))
.Named("sessionFactoryKeyProvider"));
container.Register(
Component
.For(typeof(IEntityDuplicateChecker))
.ImplementedBy(typeof(EntityDuplicateChecker))
.Named("entityDuplicateChecker"));
ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
}
}