Asp.net-Mvc-5
依賴注入結構圖 ASP.NET 標識 MVC 5
我正在使用新的 ASP.NET MVC 5 Identity 框架進行身份驗證。我傳統上使用 StructureMap 進行依賴注入,但我在連接它以使用新的 AccountController 時遇到問題。
我的 AccountController 建構子如下所示:
public AccountController() : this(new UserManager<OmpUser>(new UserStore<OmpUser>(new OmpDbContext()))) { } public AccountController(UserManager<OmpUser> userManager) { UserManager = userManager; }我的 StructureMap 配置如下所示:
public static class IoC { public static IContainer Initialize() { ObjectFactory.Initialize(x => { x.Scan(scan => { scan.TheCallingAssembly(); scan.WithDefaultConventions(); }); //x.Register<IUserStore<OmpUser>>(() => // new UserStore<OmpUser>(new OmpDbContext())); x.For<OMPEntities>().HttpContextScoped(); }); return ObjectFactory.Container; } }當我執行項目時,我收到以下錯誤:
嘗試獲取 AccountController 類型的實例時發生啟動錯誤,密鑰“”
關於如何新建一個 UserManager 對像以進行構造注入的任何想法?我試過四處尋找,但找不到太多指導。
將以下程式碼添加到您的 Container 初始化方法中。
x.For<Microsoft.AspNet.Identity.IUserStore<ApplicationUser>>() .Use<Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>>(); x.For<System.Data.Entity.DbContext>().Use(() => new ApplicationDbContext());
添加
$$ DefaultConstructor $$屬性會起作用。
public class AccountController : Controller { private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; [DefaultConstructor] //This is the attribute you need to add on the constructor public AccountController() { } // Other implementations here.......... }