Configuring Autofac to work with the ASP.NET Identity Framework in MVC 5
2016-06-10 00:47
951 查看
https://developingsoftware.com/configuring-autofac-to-work-with-the-aspnet-identity-framework-in-mvc-5
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.
Once created, use the package manager console to update the existing dependencies with the following command:
Now install the Autofac dependencies by running the following commands:
We will use this class in the next step when configuring Autofac.
As you can see from the code above we have changed the way the
First of all remove the default empty constructor and then change the controller so that there is only one constructor like so:
Now change the properties of the
Finally, we will let Autofac handle the disposal of objects by removing the
Download the AutofacIdentityExample project.
Configuring Autofac to work with the ASP.NET Identity Framework in MVC 5
By Tony Mackay 02 February 2015This 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 theIdentityConfigfile 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 theConfigurationmethod 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 theStartup.Authclass and comment out the following lines of the
ConfigureAuthmethod:
// 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 factoryCreatemethod into the constructor. Change the
ApplicationUserManagerclass 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 the
DataProtectorTokenProvidertype is resolved, so that it's injected using Autofac. Ideally, you would want to inject the
EmailServiceand
SmsServiceas well, but I have left it the way it is for this example.
Step 6: Modify the AccountController
The final step is to modify theAccountControllerso 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, and
AuthenticationManagerso 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 the
Disposeoverride.
//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 theAccountController, you should see that the dependencies have been injected, and the ASP.NET Identity framework should work as expected.
Download the AutofacIdentityExample project.
相关文章推荐
- 从零开始搭建Raspberry Pi机器视觉编程环境
- ASP.NET MVC URL重写与优化(进阶篇)-继承RouteBase玩转URL
- 约束路由 用正则表达式约束路由 Constraining a Route Using a Regular Expression 精通ASP-NET-MVC-5-弗瑞曼
- 性能工具MiniProfiler在Asp.Net WebForm跟踪EntityFramework
- AspNet Identity and IoC Container Registration
- CocoaPods和版本控制小技巧
- asp.net简单网站的实现
- Web Server 在iis下部署asp网站在iis下
- C#(asp.net)多线程用法示例(可用于同时处理多个任务)
- asp.net实现DropDownList,TreeView,ListBox的无限极分类目录树
- asp.net DataTable相关操作集锦(筛选,取前N条数据,去重复行,获取指定列数据等)
- asp.net提取多层嵌套json数据的方法
- 使用Aspose组件将WORD、PDF、PPT转为图片
- Asp.net MVC 移除不用的视图引擎
- ASP.NET Core 中文文档 第二章 指南(1)用 Visual Studio Code 在 macOS 上创建首个 ASP.NET Core 应用程序
- ASP.NET Core 中文文档 第一章 入门
- asp.net DataTable相关操作集锦(筛选,取前N条数据,去重复行,获取指定列数据等)
- 用Swashbuckle给ASP.NET Core的项目自动生成Swagger的API帮助文档
- Asp.Net中的控件(一)验证控件 和DropList选择控件
- asp.net 自带的缓存