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

放肆的年华 提交于 2020-05-15 21:31:05

问题


I cant figure out why I am getting this error below within the RegisterCollection method. Am I doing the setup incorrectly?

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:

Logger registration

 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 throws the error

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>())
});

回答1:


You are getting this error because you are calling GetInstance during your container setup. As the exception and the referenced documentation explain, this is not allowed.

The problem is caused by you trying to partially hand-wire your registrations, while you should prefer letting Simple Injector do the heavy lifting and Auto-Wire everything for you. You should therefore change your registration to the following:

container.Register<IEmailTemplatesService, EmailTemplatesService>();

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


来源:https://stackoverflow.com/questions/50176142/the-container-cant-be-changed-after-the-first-call-to-getinstance-getallinstan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!