且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC身份默认实现

更新时间:2023-02-16 10:50:34

您发现媒体链接的code负责做的依赖注入。 app.CreatePerOwinContext()为code登记在Owin管道的UserManager(代表对创建的UserManager),这实际上只是被保存在一个字典在的HttpContext

You allready found the code responsible for doing the dependency injection. app.CreatePerOwinContext() is the code for registering the usermanager (a delegate to create the usermanager) in the Owin pipeline, which is actually just a dictionary which is saved in the HttpContext.

您可以深入阅读本机制在此blogpost.

You can read in depth how this mechanism works in this blogpost.

至于您的其他问题,我完全理解!为什么检查null如果依赖注入......?好了:那是因为Owin在这里作为一个穷人的DI机制,并在默认项目模板看看究竟是怎样一个回退机制与的服务定位器反面模式。由于Owin使用一个体面的DI容器,而不是MVC pipeling需要一个默认的构造函数,因此检查为空和服务定位器是必要的。 MVC如何决定使用哪个构造是我不清楚。但我发现,有时候的UserManager注入得到,将在其他情况下的空。大概是因为owin背景是大多数只在创建账户控制器后可用的时间。

Regarding your other question which I completely understand! Why check for null if the dependency is injected...? Well: That's because Owin is used here as a poor man's DI mechanism and what you see in the default project template is actually a fallback mechanism with a smell of the service locator anti pattern. Because Owin is used instead of a decent DI container the MVC pipeling needs a default constructor, and therefore a check for null and the service locator is necessary. How MVC decides which constructor to use is not clear to me. But I found that the usermanager sometimes got injected and will be null in other scenario's. Probably because the owin context is most of the time only available after the creation of the Account controller.

虽然模板工程外的开箱它真的移动我的眉毛,就像它移动你的。于是我就用干净的实现体面DI容器中,并得到了去除大部分的owin服务定位器的东西。

While the template works out-of-the-box it really moves my eyebrows, just as it moves yours. So I went with a clean implementation of a decent DI container and got the remove most of the owin service locator stuff.

如果你有兴趣,你可以在这里找到我的解决方案 我曾经的Simple注射器的。而且还有其他DI容器解决方案这里

If your interested you can find my solution here where I used Simple Injector. And there are solutions for other DI containers here