我正在try 注册一个可以emits 东西的工厂,这样我就可以通过DI请求这个工厂的最抽象版本,然后在注册时决定实际使用什么样的东西组合.
密码:
// The thing
public interface IThing
{
void DoSomething();
}
public class ThingA : IThing
{
public void DoSomething() => throw new NotImplementedException();
}
public class ThingB : IThing
{
public void DoSomething() => throw new NotImplementedException();
}
// The factory
public interface IThingFactory<TThing> where TThing : IThing
{
TThing CreateThing();
}
public class MyThingFactory<TThing> : IThingFactory<TThing> where TThing : IThing
{
public TThing CreateThing() => throw new NotImplementedException();
}
如果我按照以下方式注册并使用这些,它就会起作用:
Services.AddSingleton<IThingFactory<ThingA>, MyThingFactory<ThingA>>();
...
var factory = ServiceProvider.GetRequiredService<IThingFactory<ThingA>>();
// factory is a MyThingFactory<ThingA>
我真正想做的是注册一些东西,以便我可以请求IThingFactory<IThing>
,但例如,以下定义无法编译:
Services.AddSingleton<IThingFactory<IThing>, MyThingFactory<ThingA>>();
与
类型"MyThingFactory"不能用作类型参数 类属类型或方法中的"Timplementation" '服务收集服务扩展.AddSingleton TService, TImplementation没有隐含参考 从"MyThingFactory"到"ITingFactory"的转换
目前尚不清楚如何注册.