Search code examples
dependency-injectioninversion-of-controlioc-containersimple-injector

Simple injector getting instance of UserStore


This is how I'm registering my identity classes:

     container.RegisterPerWebRequest<AppDbContext>();

        container.RegisterPerWebRequest<IAppUserStore>(() =>
            new AppUserStore(container.GetInstance<AppDbContext>()));

        container.RegisterPerWebRequest<AppUserManager>();


        container.RegisterPerWebRequest<AppSignInManager>();

        container.RegisterInitializer<AppUserManager>(
            manager => InitializeUserManager(manager, app));

Account controller:

 private readonly AppSignInManager _signInManager;
    private readonly AppUserManager _userManager;

    public AccountController(AppUserManager userManager, AppSignInManager signInManager )
    {
        _signInManager = signInManager;
        _userManager = userManager;
    }

Everything is good, but when I try to type something like

 var test = new Container().GetInstance<IAppUserStore>();

I get next error: No registration for type IAppUserStore could be found

But GetInstance<AppDbContext> goes ok

Why can't i get those instances? Container.Verify() compiles without errors.


Solution

  • var test = new Container().GetInstance<IAppUserStore>();
    

    Will fail because you are creating a new instance of the Container that has no registrations and therefore does not know which implementation (i.e. class) you are asking for when you say IAppUserStore (interface).

    Container().GetInstance<AppDbContext>()
    

    Will work because you are asking for a class and the Container will create an instance of a class even if it not already registered as long as the Container can resolve all of the constructor arguments of that Type.

    Try to avoid referencing the Container outside of your Composition Root. If AccountController needs IAppUserStore then you should consider adding it to the constructor of AccountController.