带有构造函数依赖注入的InvalidCastException

时间:2014-03-25 12:42:09

标签: c# visual-studio-2012 xamarin mvvmcross portable-class-library

我使用构造函数依赖注入获得了一项服务。 在构造函数中,我尝试在两种类型之间进行区分。 根据结果​​,我想将接口转换为其中一个实现。 这是构造函数:

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和type2Service实现接口IControlService。 但是,如果控件类型是Type1,我正在

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

Type2效果很好。任何想法?

2 个答案:

答案 0 :(得分:1)

您确定IoC容器传递的类型正确吗?这段代码会发生什么?

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

答案 1 :(得分:0)

感谢您的帮助!

问题出现在app.cs和像Stuart这样的IoC注册代码中。 我重命名了两个实现类并删除了“服务”结尾。 所以守则现在这样投射:

_syncService = (Type1)syncService;

并且注册看起来像这样:

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