如何將我的 Autofac 容器插入 ASP。NET 身份 2.1
我一直在研究新版本 ASP.NET Identity 2.1 的新功能,其中一項增強功能是集成到 OWIN 中間件中的新 IoC 功能。我在範例中看到的句子之一是這個:
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);這句話接收一個函式委託,它返回範例中提供的管理器實現的新實例:
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) { var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));我個人不喜歡這種實現,因為我無法使用容器為這些管理器注入我想要的任何依賴項。
還有一個“IdentityFactoryOptions”和一個“IOwinContext”被“神奇地”注入到我無法拉出到我的 IoC 容器中的函式中。
有人對此實施有更好的解決方法嗎?
我從開箱即用的 MVC5 安裝開始,並使用 AutoFac 作為 IoC 容器。聽起來我正在努力實現與您類似的目標,所以讓我解釋一下我做了什麼。作為免責聲明,我對使用 IoC 和 Identity 還很陌生。
如果您使用自己的 IoC,我相信 IOwinContext 作為 IoC 角色是不必要的 - 我切換到使用 AutoFac 註冊我的 ApplicationUserManager。為了實現這一點,我必須:
從 Startup.Auth 中刪除 CreatePerOwinContext 行,因為我將在 AutoFac 中
ApplicationDbContext註冊。ApplicationUserManager//app.CreatePerOwinContext(ApplicationDbContext.Create); //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);修改 ApplicationUserManager 建構子參數並包含來自 Create 函式的所有內容。
public ApplicationUserManager(IUserStore<ApplicationUser> store, IdentityFactoryOptions<ApplicationUserManager> options) : base(store) { //all the code from the 'Create' function here, using `this` for `manager` }將 AccountController 設置為有一個以 a
ApplicationUserManager作為參數的建構子,並UserManager廢棄ApplicationUserManager從OwinContext.private ApplicationUserManager _userManager; //every thing that needs the old UserManager property references this now public AccountController(ApplicationUserManager userManager) { _userManager = userManager; }使用 AutoFac 註冊所有內容,包括 IdentityFactoryOptions 的實例。
var x = new ApplicationDbContext(); builder.Register<ApplicationDbContext>(c => x); builder.Register<UserStore<ApplicationUser>(c => new UserStore<ApplicationUser>(x)).AsImplementedInterfaces(); builder.Register<IdentityFactoryOptions<ApplicationUserManager>(c => new IdentityFactoryOptions<ApplicationUserManager>() { DataProtectionProvider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("ApplicationName") }); builder.RegisterType<ApplicationUserManager>();這就是粗略的總結。在此過程中,我可能錯過了其他一些我必須做的調整。