我有一个如下的场景,但无法使我的SpecificApi
服务注册。
public interface IDetail
{
string Name { get; set;}
}
public class SpecificDetail : IDetail
{
public string Name { get; set; }
}
public interface IBaseApi<TDetail> where TDetail: IDetail
{
TDetail Method1();
}
public interface ISpecificApi<TDetail> : IBaseApi<TDetail> where TDetail : IDetail
{
}
public class SpecificApi : ISpecificApi<SpecificDetail>
{
public SpecificDetail Method1()
{
return new SpecificDetail();
}
}
public class Consumer
{
public Consumer(ISpecificApi<IDetail> api) // Generic must be of IDetail, not SpecificDetail
{
}
}
我尝试了以下方法注册服务,但没有成功。
// Fails at runtime with System.ArgumentException: 'Open generic service type 'DiGenericsTest.ISpecificApi`1[TDetail]' requires registering an open generic implementation type. (Parameter 'descriptors')'
builder.Services.AddSingleton(typeof(ISpecificApi<>), typeof(SpecificApi));
// Fails at build time with "there is no implicit reference conversion"
builder.Services.AddSingleton<ISpecificApi<IDetail>, SpecificApi>();
// This runs, but then I have to inject ISpecificApi<SpecificDetail> into Consumer instead of ISpecificApi<IDetail>.
builder.Services.AddSingleton<ISpecificApi<SpecificDetail>, SpecificApi>();
builder.Services.AddSingleton<Consumer>();