【问题标题】:Can not convert from System.Lazy<IARepository> to System.Lazy<IGenericRepository>无法从 System.Lazy<IARepository> 转换为 System.Lazy<IGenericRepository>
【发布时间】:2017-01-12 06:23:29
【问题描述】:

我正在尝试使用 SimpleInjector 实现延迟初始化,并使用泛型在基础构造函数中发送延迟时,我的 AService.cs 中出现错误。我读过 Lazy 不支持协方差,但我的问题是如何获得任何解决方法来将泛型与 IoC 和 Lazy 一起使用。

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

【问题讨论】:

标签: c# generics inversion-of-control repository-pattern lazy-initialization


【解决方案1】:

这里有答案:

How to downcast an instance of a Generic type?

tl;博士:

在这种情况下,编译器无法知道Bar&lt;T&gt; 可以转换为Bar&lt;Foo&gt;,因为这通常不是真的。您必须通过在两者之间引入对对象的强制转换来“作弊”:

return new FooBar&lt;Foo&gt;( (Bar&lt;Foo&gt;)(object) bar);

所以你应该能够做到这一点:

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

【讨论】:

  • 无法转换类型为“System.Lazy1[Services.Repos.IARepository]' to type 'System.Lazy1[Services.Repos.IGenericRepository]”的对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2013-03-04
  • 1970-01-01
相关资源
最近更新 更多