Search code examples
c#visual-studio-2012xamarinmvvmcrossportable-class-library

InvalidCastException with Constructor Dependency Injection


I got a service using constructor dependecy injection. In the constructor i try to differ between two types. Depending on the result i want to cast the interface to one of it's implementations. here's the constructor:

private readonly IControlService _syncService;

    public CacheService(IControlService syncService)
    {

        if (Config.Config.type == ControlType.Type1) 
        {
            try
            {
                _syncService = (type1Service)syncService;
            }
            catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.ToString()); }
        }
        else if (Config.Config.type == ControlType.Type2)
        {

            _syncService = (type2Service)syncService;
        }  
    }

Both - type1Service and type2Service implement the interface IControlService. However, if control type ist Type1, i'm getting

03-25 12:38:15.503 I/mono-stdout( 2542): System.InvalidCastException: Cannot cast from source type to destination type.

Type2 works well. Any Ideas?


Solution

  • Thanks for your help!

    Problem was in the app.cs and the IoC registration Code like Stuart assumed. I renamed the two Implementation Classes and removed the 'Service' ending. So the Code now casts like this:

    _syncService = (Type1)syncService;

    and the Registration looks like that:

    public override void Initialize()
        {
            CreatableTypes()
                .EndingWith("Service")
                .AsInterfaces()
                .RegisterAsLazySingleton();
    
            if(Config.Config.type == ControlType.Type1)
            {
                Mvx.RegisterType<IControlService, Type1>();
            }
            else if (Config.Config.type == ControlType.Type2)
            {
                Mvx.RegisterType<IControlService, Type2>();
            }
    
            RegisterAppStart<ViewModels.FirstViewModel>();
        }