如何使用config在Catel ServiceLocator中注册类型?

时间:2015-11-16 07:59:10

标签: catel

我尝试使用app.config在ServiceLocator中注册类型,例如UIVisualizerService类型。

  1. 首先,我检查是否在ServiceLocator.Default中注册了该类型。它被注册了。
  2. 然后我删除其注册并再次检查。正如所料,它没有被注册。
  3. 然后我运行ioc.DefaultServiceLocatorConfiguration.Configure(serviceLocator)来再次注册类型(在app.config中配置)。
  4. 当我再次检查时,类型未注册!
  5. 问题是: ioc.DefaultServiceLocatorConfiguration.Configure(serviceLocator)正常工作,但UIVisualizerService未注册。

    App.xaml.cs中的代码出了什么问题?

    var serviceLocator = ServiceLocator.Default;
    bool canResolveType = serviceLocator.IsTypeRegistered(typeof(IUIVisualizerService));
    if (canResolveType)
    {
        //Expected behaviour
        serviceLocator.RemoveAllTypes(typeof(IUIVisualizerService));
        canResolveType = serviceLocator.IsTypeRegistered(typeof(IUIVisualizerService));
        if (!canResolveType)
        {
            //Expected behaviour
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var ioc = configuration.GetSection<IoCConfigurationSection>("ioc", "catel");
            //<catel>
            //  <ioc>
            //    <serviceLocatorConfigurations>
            //      <serviceLocatorConfiguration>
            //        <register interfaceType="Catel.Services.IUIVisualizerService" 
            //                  implementationType="Catel.Services.UIVisualizerService, Catel.MVVM" />          
            //      </serviceLocatorConfiguration>
            //    </serviceLocatorConfigurations>
            //  </ioc>
            //</catel>
            try
            {
                ioc.DefaultServiceLocatorConfiguration.Configure(serviceLocator); // to register UIVisualizerService again
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("Error in App.xaml.cs, in serviceLocatorConfiguration : {0}", ex.Message));
                // if incorrect implementationType
                // ex.Message = "Argument 'serviceImplementationType' cannot be null ..."
            }
            canResolveType = serviceLocator.IsTypeRegistered(typeof(IUIVisualizerService));
            if (!canResolveType)
            {
                //Unexpected behaviour
                Console.WriteLine("Unexpected behaviour"); // It works !!!
            }
            else
            {
                //Expected behaviour
                // should be here !!!
            }
        }
    }
    

0 个答案:

没有答案