我正在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"的转换

目前尚不清楚如何注册.

推荐答案

如果您使用out关键字在界面上启用协方差,您将能够注册服务.

//                              +--- Add this
//                              |
public interface IThingFactory<out TThing> where TThing : IThing
{
    TThing CreateThing();
}

然后您可以从IThingFactory<ThingA>隐式转换为IThingFactory<IThing>,这将允许注册该类型.像这样:

Services.AddSingleton<IThingFactory<IThing>, MyThingFactory<ThingA>>();

Csharp相关问答推荐

使用LayoutKind在C#中嵌套 struct .显式

S能够用DATETIME来计算,这有什么错呢?

从c#列表中删除额外的对象&对象&>从ASP.NET WebForm返回json响应

无法创建';';类型的';DbContext';.异常';无法解析类型';Microsoft.EntityFrameworkCore.DbContextOptions`1[Comm的服务

JSON空引用异常仅在调试器中忽略try-Catch块,但在其他上下文中捕获得很好

TCPClient阅读流

C#和ASP.NET核心标识:提高GetUserAsync调用的性能

当索引和外键是不同的数据类型时,如何设置导航属性?

.NET并发词典交换值

正在try 从Blazor中的API读取JSON

如何在我的C#应用程序中设置带有reactjs前端的SignalR服务器?

为什么我可以用硬编码的集合而不是变量来设置没有setter的IList属性的值?

具有类型识别的泛型方法

如何返回具有泛型的类?

在';、';附近有错误的语法.必须声明标量变量";@Checkin";.';

用于请求用户返回列表的C#Google API

在C#和HttpClient中使用REST API

与另一个对象位于同一位置的对象具有不同的变换位置

缩写的MonthNames有问题

Windows 10上埃及标准时间的时区偏移不正确