简体   繁体   中英

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?

Are you sure the IoC container is passing in correct type? What happens with this code?

    if (Config.Config.type == ControlType.Type1) 
    {
        var s = syncService as type1Service;

        if (s == null)
        {
            throw new ArgumentException (
                string.Format ("Expected type: {0}, Actual type: {1}", 
                    typeof(type1Service), 
                    syncService.GetType ()));
        }
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM