0

생성자 종속적 인 주입을 사용하는 서비스가 있습니다. 생성자에서 나는 두 가지 유형을 다르게하려고합니다. 결과에 따라 인터페이스 중 하나를 구현하려고합니다. type1Service 및 type2Service이 인터페이스 IControlService를 구현 -InvalidCastException - 생성자 종속성 삽입

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

모두 : 여기 생성자입니다. 그러나, 제어 유형 표준시 타입 1, 내가 타입 2는 잘 작동

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

을 얻고있다. 어떤 아이디어?

+0

당신이 보여 코드가 잘 보인다. 완전히 재건 한거야? 어딘가에 비슷한 정적 참조가 없습니까? syncService를 디버그하고 검사하면 이상하거나 이상한 것을 보지 못합니까? – Johan

+0

나는 그것을 모두했다. 문제는 MvvmCross ioc와 인터페이스의 이중 구현과 관련이 있습니다. – flo1411

+0

필자는 그 중 하나를 사용하지 않았지만 다른 상황에서는 문제가없는 상황을 사용했습니다 (autofac은 시도한 최신 ioc이었습니다). 문제가 될 수 있다면 이상하지만 코드를 게시하면 다른 사람이 볼 수 있습니다. 어떤 것. – Johan

답변

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