【问题标题】:InvalidCastException with Constructor Dependency Injection带有构造函数依赖注入的 InvalidCastException
【发布时间】:2014-03-25 12:42:09
【问题描述】:

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

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

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 运行良好。有什么想法吗?

【问题讨论】:

  • 您显示的代码看起来不错。您是否进行了全面重建?某处没有旧的静态引用或类似的东西?如果您调试并检查 syncService,您没有发现任何错误或奇怪之处?
  • 我已经完成了所有这些。猜猜,问题出在 MvvmCross ioc 和接口的双重实现上。
  • 我没用过那个,但是我在类似的情况下用过其他的没有问题(autofac是我尝试过的最新的ioc),如果这会是一个问题会很奇怪,但也许你应该发布该代码,有人可能会看到一些东西。
  • 你如何告诉 IoC 容器要创建哪个 IControlService?您能否编辑问题以包含您的 IoC 注册码 - 我想这也会以某种方式打开 Config.Config.type

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


【解决方案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 ()));
        }
    }

【讨论】:

    【解决方案2】:

    感谢您的帮助!

    问题出在 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>();
        }
    

    【讨论】:

      猜你喜欢
      • 2015-07-22
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      相关资源
      最近更新 更多