Configuring Autofac to work with the ASP.NET Identity Framework in MVC 5
https://developingsoftware.com/configuring-autofac-to-work-with-the-aspnet-identity-framework-in-mvc-5
Configuring Autofac to work with the ASP.NET Identity Framework in MVC 5
By Tony Mackay 02 February 2015
This post will show you how to modify the default MVC 5 template, so that it uses Autofac to inject the ASP.NET Identity dependencies into the Account Controller.
This post assumes you already know how to create a new ASP.NET MVC 5 project, if not, see the post: How to Create an ASP.NET MVC 5 Web Application.
Step 1: Create new ASP.NET MVC 5 application and Install Dependencies
First create a new MVC 5 project using the default settings. I have named the project AutofacIdentityExample, which you can download from here.
Once created, use the package manager console to update the existing dependencies with the following command:
Update-Package
Now install the Autofac dependencies by running the following commands:
Install-Package Autofac.Mvc5
Install-Package Autofac.Mvc5.Owin
Step 2: Create a custom ApplicationUserStore
Open the IdentityConfig
file and then create the following class:
public class ApplicationUserStore : UserStore<ApplicationUser>
{
public ApplicationUserStore(ApplicationDbContext context)
: base(context)
{
}
}
We will use this class in the next step when configuring Autofac.
Step 3: Modify the Startup class to register dependencies with Autofac
Modify the Configuration
method so that it looks like the following:
public void Configuration(IAppBuilder app)
{
var builder = new ContainerBuilder();
// REGISTER DEPENDENCIES
builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerRequest();
builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
builder.RegisterType<ApplicationSignInManager>().AsSelf().InstancePerRequest();
builder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();
// REGISTER CONTROLLERS SO DEPENDENCIES ARE CONSTRUCTOR INJECTED
builder.RegisterControllers(typeof(MvcApplication).Assembly);
// BUILD THE CONTAINER
var container = builder.Build();
// REPLACE THE MVC DEPENDENCY RESOLVER WITH AUTOFAC
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// REGISTER WITH OWIN
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
ConfigureAuth(app);
}
Step 4: Modify the Startup.Auth class
The next step is to comment out the code that is used to register the dependencies manually through OWIN. Open the Startup.Auth
class and comment out the following lines of the ConfigureAuth
method:
// Configure the db context, user manager and signin manager to use a single instance per request
//app.CreatePerOwinContext(ApplicationDbContext.Create);
//app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
//app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
Step 5: Modify the ApplicationUserManager
In this step, we need to move the configuration code from the factory Create
method into the constructor. Change the ApplicationUserManager
class to look like this:
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store, IDataProtectionProvider dataProtectionProvider)
: base(store)
{
UserValidator = new UserValidator<ApplicationUser>(this)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
UserLockoutEnabledByDefault = false;
//DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
//MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
EmailService = new EmailService();
SmsService = new SmsService();
UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
}
As you can see from the code above we have changed the way theDataProtectorTokenProvider
type is resolved, so that it's injected using Autofac. Ideally, you would want to inject the EmailService
and SmsService
as well, but I have left it the way it is for this example.
Step 6: Modify the AccountController
The final step is to modify the AccountController
so that there is only one constructor, and so that the properties that use the Identity framework are no longer resolved using the service locator pattern.
First of all remove the default empty constructor and then change the controller so that there is only one constructor like so:
private readonly ApplicationUserManager _userManager;
private readonly ApplicationSignInManager _signInManager;
private readonly IAuthenticationManager _authManager;
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, IAuthenticationManager authManager)
{
_userManager = userManager;
_signInManager = signInManager;
_authManager = authManager;
}
Now change the properties of the SignInManager
, UserManager
, andAuthenticationManager
so that they are readonly with no service location.
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager;
}
}
private IAuthenticationManager AuthenticationManager
{
get
{
return _authManager;
}
}
Finally, we will let Autofac handle the disposal of objects by removing theDispose
override.
//protected override void Dispose(bool disposing)
//{
// if (disposing)
// {
// if (_userManager != null)
// {
// _userManager.Dispose();
// _userManager = null;
// }
// if (_signInManager != null)
// {
// _signInManager.Dispose();
// _signInManager = null;
// }
// }
// base.Dispose(disposing);
//}
Conclusion
That's all there is to it. Now, if you put a breakpoint on the first line of the constructor, inside the AccountController
, you should see that the dependencies have been injected, and the ASP.NET Identity framework should work as expected.
Download the AutofacIdentityExample project.
Configuring Autofac to work with the ASP.NET Identity Framework in MVC 5的更多相关文章
- 【ASP.NET Identity系列教程(三)】Identity高级技术
注:本文是[ASP.NET Identity系列教程]的第三篇.本系列教程详细.完整.深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序 ...
- 从0引入 ASP.NET Identity Core
原文出自Rui Figueiredo的博客,原文链接<ASP.NET Identity Core From Scratch> 译者注:这篇博文发布时正值Asp.Net Core 1.1 时 ...
- 自定义 ASP.NET Identity Data Model with EF
One of the first issues you will likely encounter when getting started with ASP.NET Identity centers ...
- ASP.NET Identity 三(转载)
转载来源:http://www.cnblogs.com/r01cn/p/5194257.html 注:本文是[ASP.NET Identity系列教程]的第三篇.本系列教程详细.完整.深入地介绍了微软 ...
- 【译】ASP.NET Identity Core 从零开始
原文出自Rui Figueiredo的博客,原文链接<ASP.NET Identity Core From Scratch> 译者注:这篇博文发布时正值Asp.Net Core 1.1 时 ...
- ASP.Net Core 2.2 MVC入门到基本使用系列 (三)
本教程会对基本的.Net Core 进行一个大概的且不会太深入的讲解, 在您看完本系列之后, 能基本甚至熟练的使用.Net Core进行Web开发, 感受到.Net Core的魅力. 本教程知识点大体 ...
- ASP.NET Identity系列教程-4【Identity高级技术】
https://www.cnblogs.com/r01cn/p/5194257.html 15 ASP.NET Identity高级技术 In this chapter, I finish my de ...
- 从Membership 到 .NET4.5 之 ASP.NET Identity
我们前面已经讨论过了如何在一个网站中集成最基本的Membership功能,然后深入学习了Membership的架构设计.正所谓从实践从来,到实践从去,在我们把Membership的结构吃透之后,我们要 ...
- MVC5 - ASP.NET Identity登录原理 - Claims-based认证和OWIN
在Membership系列的最后一篇引入了ASP.NET Identity,看到大家对它还是挺感兴趣的,于是来一篇详解登录原理的文章.本文会涉及到Claims-based(基于声明)的认证,我们会详细 ...
随机推荐
- Hibernate 系列 05 - Session 类
引导目录: Hibernate 系列教程 目录 前言: Session是Hibernate运作的中心,对象的生命周期.事务的管理.数据库的存取都与Session息息相关. 就如同在编写JDBC时需要关 ...
- 【RDA】使用RDA(Remote Diagnostic Agent)工具对数据库进行健康检查
[RDA]使用RDA(Remote Diagnostic Agent)工具对数据库进行健康检查 分类: Linux RDA英文全称叫做"Oracle Remote Diagnostic Ag ...
- SQLite学习笔记(十一)&&虚拟机原理
前言 我们知道任何一种关系型数据库管理系统都支持SQL(Structured Query Language),相对于文件管理系统,用户不用关心数据在数据库内部如何存取,也不需要知道底层的存储 ...
- Windows下磁盘分配操作
问题概述:在装系统的时候有时候并不能一下分出完全符合我们使用习惯的分区大小,我们可能需要在后期调整分区大小.以下是有关分区大小调整的操作. 使用工具:Windows磁盘管理工具. 操作步骤: 1.使用 ...
- 异步方法的意义何在,Async和await以及Task的爱恨情仇,还有多线程那一家子。
前两天刚感受了下泛型接口的in和out,昨天就开始感受神奇的异步方法Async/await,当然顺路也看了眼多线程那几个.其实多线程异步相关的类单个用法和理解都不算困难,但是异步方法Async/awa ...
- Docker初体验
## Docker初体验 安装 因为我用的是mac,所以安装很简单,下载dmg下来之后拖拽安装即可完成. 需要注意的就是由于之前的docker是基于linux开发,不支持mac,所以就出现了docke ...
- C#进阶系列——WebApi 异常处理解决方案
前言:上篇C#进阶系列——WebApi接口传参不再困惑:传参详解介绍了WebApi参数的传递,这篇来看看WebApi里面异常的处理.关于异常处理,作为程序员的我们肯定不陌生,记得在介绍 AOP 的时候 ...
- git上传新项目
命令行指令 Git 全局设置 git config --global user.name "15510728111" git config --global user.email ...
- 用vue.js学习es6(一):基本工具及配置
一.工具: sublime,node.js,npm 1.安装sublime 的es6插件: (1).在sublime中按Ctrl+`调出console (2).粘贴以下代码到底部命令行并回车(subl ...
- 利用StringEscapeUtils对字符串进行各种转义与反转义(Java)
apache工具包common-lang中有一个很有用的处理字符串的工具类,其中之一就是StringEscapeUtils,这个工具类是在2.3版本以上加上的去的,利用它能很方便的进行html,xml ...