0

SimpleInjectorで怠惰な初期化を行い、Genericsを使用しようとしています。AService.csでLazy内部のコンストラクタを送信中にエラーが発生します。私はLazyが共分散をサポートしていないと読んでいますが、私の質問は、IoCとLazyでジェネリックスを使用する回避策を得る方法です。System.Lazy <IARepository>からSystem.Lazy <IGenericRepository>に変換できません

AService.cs

public class AService : GenericService, IAService 
{ 
    private readonly Lazy<IARepository> aRepository; 
    public AService(Lazy<IARepository> aRepository) : base(aRepository) 
    { 
     this.aRepository = aRepository; 
    } 
} 

IAService.cs

public interface IAService : IGenericService 
{ 
} 

IGenericService.cs

public interface IGenericService 
{ 
    void DoSomething(); 
} 

GenericService.cs

public class GenericService : IGenericService 
{ 
    private readonly Lazy<IGenericRepository> genericRepository; 
    public GenericService(Lazy<IGenericRepository> genericRepository) 
    { 
     this.genericRepository = genericRepository; 
    } 
    public void DoSomething() 
    { 
     genericRepository.Value.DoSomething(); 
    } 
} 
シンプルなインジェクターでの

バインディング

container.Register<Lazy<IARepository>>(
    () => new Lazy<IARepository>(container.GetInstance<ARepository>)); 
container.Register<Lazy<IBRepository>>(
    () => new Lazy<IBRepository>(container.GetInstance<BRepository>)); 
container.Register<Lazy<IAService>>(
    () => new Lazy<IAService>(container.GetInstance<AService>)); 
+0

可能な重複します。http: //stackoverflow.com/questions/21117619/covariant-use-of-generic-lazy-class-in-c-sharp – Michael

+0

関連項目https://msdn.microsoft.com/en-us/library/dd799517(v= vs.110).aspx – Michael

答えて

1

これは、ここで回答されています

How to downcast an instance of a Generic type?

TL; DR:

コンパイラはBar<T>Bar<Foo>にキャストできることを知ることができませんこの場合は一般的に真実ではないためです。だから、あなたが行うことでこれを達成することができるはず

return new FooBar<Foo>((Bar<Foo>)(object) bar);

:あなたが間にあるオブジェクトにキャストを導入することにより、「カンニング」する必要が

public AService(Lazy<IARepository> aRepository) : base((Lazy<IGenericRepository>)(object)aRepository) { }

+0

タイプ 'System.Lazy'1のオブジェクトをキャストすることができません。[Services.Repos.IAR [System.Lazy'1 [Services.Repos.IGenericRepository] ​​'と入力してください。 – BilalArshad

関連する問題