ServiceLocator not initialized in Tests project

梦想与她 提交于 2019-12-24 10:03:04

问题


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));
}
}

回答1:


You are registering DefaultSessionFactoryKeyProvider as an implementation of DefaultSessionFactoryKeyProvider, while you have a dependency on ISessionFactoryKeyProvider, which castle windsor doesn't know how to resolve as no implementations has been registered for that interface.

I think that should be:

container.Register( Component .For(typeof(ISessionFactoryKeyProvider)) .ImplementedBy(typeof(DefaultSessionFactoryKeyProvider)) .Named("sessionFactoryKeyProvider"));




回答2:


Is Castle.Core referenced by your test project?



来源:https://stackoverflow.com/questions/6473728/servicelocator-not-initialized-in-tests-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!