我是以下代码
public void Test()
{
// Configure DI
IServiceCollection services = new ServiceCollection();
services.AddTransient<IEngine<MetaData>, myEngine>();
// Tried
// services.AddTransient(typeof(IEngine<>), typeof(Engine<MetaData>));
var provider = services.BuildServiceProvider();
// Request Instance from DI, at this point I dont want to have to that
// tell it I want and Engine with a MetaData
var engine1 = provider.GetRequiredService <IEngine<MetaData>>();
}
我的课程看起来像
public class myEngine : IEngine<MetaData>
{
public IReader<MetaData> Reader { get; set; }
}
public class MetaData
{
public int Age { get; set; }
public string Name { get; set; }
}
public class Engine<T> : IEngine<T>
{
public IReader<T> Reader { get; set; }
public Engine(IReader<T> reader)
{
Reader = reader;
}
}
public interface IReader<T>
{
T MetaData { get; set; }
}
public interface IEngine<T>
{
IReader<T> Reader { get;set;}
}
我更喜欢这段代码,因为我不在乎T是什么
var engine2 = provider.GetRequiredService(typeof(IEngine<>));