simpleinjector / SimpleInjector

An easy, flexible, and fast Dependency Injection library that promotes best practice to steer developers towards the pit of success.
https://simpleinjector.org
MIT License
1.21k stars 155 forks source link

RegisterInitializer Documentation does not match actual behavior #974

Closed polarius11 closed 8 months ago

polarius11 commented 1 year ago

According to the documentation (https://simpleinjector.org/ReferenceLibrary/html/M_SimpleInjector_Container_RegisterInitializer__1.htm), the RegisterInitializer-method works only with instances that are created by the container self (using constructor injection).

But when I run the following Tests, the initializer is also called (using SimpleInjector 5.4.1):

[TestMethod]
public void RegisterInitializerForRegisterSingleWithConcreteInstance_InitializerCalledOnce()
{
    using var container = new Container();
    int initializerCallCount = 0;

    container.RegisterInstance<IMyService>(new MyServiceWithSubscriber());
    container.RegisterInitializer<IMyService>(_ => initializerCallCount++);

    _ = container.GetInstance<IMyService>();

    Assert.AreEqual(1, initializerCallCount);
}

[TestMethod]
public void RegisterInitializerForRegisterSingleWithFactoryFunc_InitializerCalledOnce()
{
    using var container = new Container();
    int initializerCallCount = 0;

    container.RegisterSingleton<IMyService>(() => new MyServiceWithSubscriber());
    container.RegisterInitializer<IMyService>(_ => initializerCallCount++);

    _ = container.GetInstance<IMyService>();

    Assert.AreEqual(1, initializerCallCount);
}

Is this behavior intended and the documentation outdated?

dotnetjunkie commented 1 year ago

This information is outdated. I tried to track down when the change was made, but couldn't easily track this change back to a release. The change very likely happened before the v3 release (which was released on Aug 18, 2015). This means that this information is unfortunately outdated for a very long time. I just updated the source code and will push this shortly.

However, keep in mind that we stopped updating the reference library on n simpleinjector.org/ReferenceLibrary/ since version 5.3.0. It isn't updated any longer. The documentation on simpleinjector.org/documentation does not link to the ReferenceLibrary any more.

polarius11 commented 1 year ago

Thanks for your quick response and fix!