Search code examples
c#catel

Use Catel ServiceLocator in constructor of control


I have GridControl and want to use the ServiceLocator.Default instance to retrieve objects (e.g. IMessageService) in the contructor of the control. No problem at run-time but the control throws an exception at design time - the control does not shows up in the Visual Studio designer.

A not-null check on ServiceLocator.Default does not help. How can I use the service locator in the ctor of the control with full designer support?

public MyGridControl()
    {
        if (ServiceLocator.Default != null)
        {
            this.mySettingService = ServiceLocator.Default.ResolveType<IRosySettingService>();
            if (this.mySettingService != null)
            {
                var mediator = ServiceLocator.Default.ResolveType<IMessageMediator>();
                mediator.Register<String>(this, SaveSettings, MessageKeys.SaveGridSettings);
            }
        }
    }

Thanks!

Stefan


Solution

  • You should prevent code from running in the designer. You can do it as follows:

    public MyGridControl()
    {
        if (CatelEnvironment.IsInDesignMode)
        {
            return;
        }
    
        // TODO: Use service locator and all runtime code
    }