One reason I love .NET Core is the out-of-box dependency injection it provides. Unfortunately I’m not allowed to use .NET Core due to some backward compatibility requirements.
Simple Injector comes to the rescue, but there was a catch when it comes to dynamically injecting DbContext.
The default template with Identity generated by MVC 5 (mainly Startup_auth.cs, AccountController and ManageController), Simple Injector just refused to work with it. While there are some solutions available online 12, none of them worked for me.
Although the solutions online didn’t work for me, I managed to gather enough information to make my own solution. This GitHub issue1 provides almost everything I need, except it’s based on an older version of Simple Injector, so some syntax changes were required.
Follow the post you should be able to:
Prepare ApplicationUserManager, UserStore and ApplicationSignInManager for AccountController and ManageController, by removing some badly written (and anti-pattern, and violating SOLID, and…) codes generated
Get an OwinContext for ApplicationUserManager in Startup_auth.cs
Expect some errors:
To fix the above errors, I used the latest syntax found on from Simple Injector’s documentation
Some key changes are:
container.RegisterSingle<IAppBuilder>(app); was simplified to container.RegisterInstance(app);
container.RegisterPerWebRequest<ApplicationUserManager>(); became container.Register<ApplicationUserManager>(Lifestyle.Scoped);, where Lifestyle.Scoped is defined beforehand container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
ApplicationUserManager needs a static methodf or initialisation, see code below
The same applies for UserStore
A little hack to bypass container.verfiy(), because OwinContext doesn’t exist at the verification stage due to the lack ofHttpContext.Current
The complete SimpleInjectorInitializer.cs(or you can put the code in Startup.cs, I just don’t like adding stuff to it) file looks like this: