Search code examples
c#.netc#-4.0dependency-injectionsimple-injector

Why does this DI code declare a method-scope var and then assign it to a static, class-level object?


.Net-wise, I've been stuck in 2005 until just recently. I know I have a lot of catching up to do but since I don't like inefficient code, the following code snippet (at the bottom of this question) from the SimpleInjector tutorial has me a bit stumped.

The problem is within the BootStrapper() method, which is used to intialize a static SimpleInjector container.

Within this method, a var container is declared and assigned a new Container(). At the end of the method, the method-scope container is then assigned to the static, App level container variable.

Why is this done this way? There must be a good reason for assigning the container first to a local-scope var and then, finally, assigning the var to the class-level, static Container variable. To me, this seems like an obvious, redundant assignment, but if that's the case, I doubt anyone would do it this way. What am I missing?

The code, below, is from the code from the SimpleInjector documentation. I understand all of what the code is doing, I just don't understand the point of this extra var assignment.

using System.Windows;
using SimpleInjector;

public partial class App : Application
{
    private static Container container; //<-- The static, class-level variable. 
                                        //    Why not assign to it from the get-go?!

   //...snip...

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        Bootstrap();
    }

    private static void Bootstrap()
    {
        // Create the container as usual.
        var container = new Container();  //What's the point of this var?

        // Register your types, for instance:
        container.RegisterSingle<IUserRepository, SqlUserRepository>();
        container.Register<IUserContext, WpfUserContext>();

        // Optionally verify the container.
        container.Verify();

        // Store the container for use by the application.
        App.container = container;  //Couldn't we have done this from line 1 of this method?
    }
}

Source: SimpleInjector - Windows Presentation Foundation Integration Guide


Solution

  • If the container is assigned to the static property at once, then the static property would reference a container that is not yet fully initialized, which could have unwanted consequences.

    Assigning the container to the static property only when it is fully initialized prevents others from using a partially initialized container.