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
ManageController), Simple Injector just refused to work with it. While there are some solutions available online 1 2, 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:
ManageController, by removing some badly written (and anti-pattern, and violating SOLID, and…) codes generated
- Get an OwinContext for
- Expect some errors:
'SimpleInjectorWebExtensions.RegisterPerWebRequest<TService>(Container, Func<TService>)' is obsolete: 'RegisterPerWebRequest has been deprecated. Please use Register<TService>(Func<TService>, Lifestyle.Scoped) instead. See: https://simpleinjector.org/mvc' 'Container' does not contain a definition for 'RegisterSingle' and no extension method 'RegisterSingle' accepting a first argument of type 'Container' could be found (are you missing a using directive or an assembly reference?)
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
Lifestyle.Scopedis defined beforehand
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
ApplicationUserManagerneeds a static methodf or initialisation, see code below
The same applies for
- A little hack to bypass
OwinContextdoesn’t exist at the verification stage due to the lack of
SimpleInjectorInitializer.cs(or you can put the code in
Startup.cs, I just don’t like adding stuff to it) file looks like this: