第一次调用 GetInstance、GetAllInstances、Verify 和 GetRegistration 的一些调用后容器不能改变

The container can't be changed after the first call to GetInstance, GetAllInstances, Verify, and some calls of GetRegistration

我无法弄清楚为什么在 RegisterCollection 方法中会出现以下错误。我是不是设置有误?

The container can't be changed after the first call to GetInstance, GetAllInstances, Verify, and some calls of GetRegistration. Please see https://simpleinjector.org/locked to understand why the container is locked. The following stack trace describes the location where the container was locked:

记录器注册

 public static void Register(Container container)
 {
     container.RegisterConditional(typeof(ILogger), 
        c => typeof(NLogLogger<>).MakeGenericType(
            c.Consumer?.ImplementationType ?? typeof(object)),
        Lifestyle.Transient, 
        c => true);

...

}

container.RegisterCollection 抛出错误

container.Register<IEmailTemplatesService>(() => new EmailTemplatesService(emailTemplates,
    container.GetInstance<IEventEmailTemplatesRepository>(),
    container.GetInstance<IEmailTemplatesRepository>(),
    container.GetInstance<IEventSettingsRepository>(),
    container.GetInstance<IEmailsService>(),
    container.GetInstance<IUnitOfWork>(),
    container.GetInstance<IValidationProvider>()));

container.RegisterCollection<IStreamingMethod>(new List<IStreamingMethod>
{
    new CubeProvider(container.GetInstance<ILogger>()),
    new BallerTvProvider(container.GetInstance<ILogger>())
});

您收到此错误是因为您在容器设置期间调用了 GetInstance。正如例外情况和参考文档所解释的那样,这是不允许的。

问题是由于您尝试部分手动连接您的注册,而您应该更愿意让 Simple Injector 为您完成繁重的工作并自动连接所有内容。因此,您应该将注册更改为以下内容:

container.Register<IEmailTemplatesService, EmailTemplatesService>();

container.RegisterCollection<IStreamingMethod>(new[]
{
    typeof(CubeProvider),
    typeof(BallerTvProvider)
});