为什么 GetCurrentRegistrations 不是 return 我的开放通用注册

Why does GetCurrentRegistrations not return my open generic registration

我无法理解调用 GetCurrentRegistrations.

后 return 到底得到了什么

我想要完成的是确定 Register 调用之前是否已经被调用过。在那种情况下,我想跳过并继续。容器在这个过程中没有被锁定是很重要的!

例如:

var container = new Container();
container.Register(typeof(IFoo), typeof(Foo), Lifestyle.Transient);
var currentRegistrations = container.GetCurrentRegistrations();
if (currentRegistrations.Any(r => producer.ServiceType == typeof(ICommandHandler<>))
{
    // skip
}

以上内容似乎运行良好。但是,当类型是开放通用的时,对 GetCurrentRegistrations 的调用不会 return 注册:

var container = new Container();
container.Register(typeof(ICommandHandler<>), typeof(CommandHandler<>), Lifestyle.Transient);
var currentRegistrations = container.GetCurrentRegistrations();
if (currentRegistrations.Any(r => producer.ServiceType == typeof(ICommandHandler<>))
{
    // currentRegistrations is empty, so we are not getting here :-(
}

是否有另一种方法可以确定这一点(不锁定容器)?

看看 return 类型,GetCurrentInstanceProducers 不是更好的名字吗?想一想……(也许现在部分回答了我自己的问题)可能是实际的 InstanceProducers 还不能用于开放通用注册吗?

GetCurrentRegistrations 不能 return 开放通用注册,因为 InstanceProducer 只存在于一个封闭通用类型。因此,一个单一的开放式通用注册可能会导致数百个 InstanceProducer 实例。 Simple Injector 中的开放泛型是通过未注册的类型解析来完成的,这意味着构造类似于具有事件。如果解决了不存在显式注册的封闭通用类型,Simple Injector 会检查是否存在匹配的开放通用注册。仅在最后一刻,InstanceProducer 被创建。

所以您不能使用 GetCurrentRegistrations 来完成这项工作。在您的情况下,您最好在容器中设置一个标志以允许跳过注册。例如:

private static readonly object key = new object();

public static void MyExtensionMethod(this Container container)
{

    if (container.ContainerScope.GetItem(key) is null)
    {
        // do registrations here
        container.ContainerScope.SetItem(key, new object());
    }
}