gpt4 book ai didi

c# - 使用 Autofac 注册实现变体泛型接口(interface)的具体类型

转载 作者:行者123 更新时间:2023-11-30 17:55:47 25 4
gpt4 key购买 nike

考虑将以下结构作为 Autofac 3.0.0 的注册主题:

class Something
{
public int Result { get; set; }
}

class SomethingGood : Something
{
private int _good;
public int GoodResult {
get { return _good + Result; }
set { _good = value; }
}
}

interface IDo<in T> where T : Something
{
int Calculate( T input );
}

class MakeSomethingGood : IDo<SomethingGood>
{
public int Calculate( SomethingGood input ) {
return input.GoodResult;
}
}

class ControlSomething
{
private readonly IDo<Something> _doer;
public ControlSomething( IDo<Something> doer ) {
_doer = doer;
}

public void Show() {
Console.WriteLine( _doer.Calculate( new Something { Result = 5 } ) );
}
}

我正在尝试注册具体类型 MakeSomethingGood,然后通过逆变接口(interface)解析它。

var builder = new ContainerBuilder();
builder.Register( c => new MakeSomethingGood() ).As<IDo<SomethingGood>>();
builder.Register( c => new ControlSomething( c.Resolve<IDo<Something>>() ) ).AsSelf();

var container = builder.Build();
var controller = container.Resolve<ControlSomething>();

... 和 Resolve失败,因为没有找到 IDo<Something> 的组件

我做错了什么?

谢谢

最佳答案

您注册一个 IDo<SomethingGood>并尝试解决 IDo<Something> .那应该如何工作?为此,IDo<T>应定义为协变:IDo<out T> .

IDo<in T>被定义为逆变(使用 in 关键字),你不能简单地分配一个 IDo<SomethingGood>IDo<Something> .这不会在 C# 中编译:

IDo<SomethingGood> good = new MakeSomethingGood();

// Won't compile
IDo<Something> some = good;

这就是 Autofac 无法解析它的原因,即使使用 ContravariantRegistrationSource .

关于c# - 使用 Autofac 注册实现变体泛型接口(interface)的具体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14716811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com