当前位置: 首页 > 编程语言 > C#

为ASP.NET身份共享配置UnityDI

时间:2023-04-10 14:31:24 C#

为ASP.NET身份配置UnityDI种类。设置是这样的:publicclassAccountController:ApiController{privateUserManager_userManager{get;放;}publicAccountController(UserManageruserManager){if(userManager==null){thrownewArgumentNullException("userManager");}_userManager=userManager;}//...}为Unity使用这些配置:unity.RegisterType();unity.RegisterType(newHierarchicalLifetimeManager());unity.RegisterType(newHierarchicalLifetimeManager());这与Autofac相同,例如与Ninject的其他帖子相同,但在我的情况下不起作用。错误消息是:尝试创建“AccountController”类型的控制器时出错。确保控制器有一个无参数的公共构造函数。手动创建当然是:publicAccountController():this(newUserManager(newUserStore("Mongo"))){}怎么了?更新正如@emodendroket所建议的那样,缩短代码就可以了。不需要Unity.Mvc包。unity.RegisterType(newHierarchicalLifetimeManager());andpublicAccountController(UserManager_userManager,IAccountRepository_account){//...你还需要解析UserManager。以下是如何使用UserManager和RoleManager执行此操作的示例。在这个例子中,我使用的是常规的Unity3包,而不是fork或引导程序之一(过去有一些问题)。AccountControllerprivatereadonlyUserManager_userManager;私有只读RoleManager_roleManager;publicAccountController(IUserStoreuserStore,IRoleStoreroleStore){_userManager=newUserManager(userStore);_roleManager=newRoleManager(roleStore);UnityBootstrappervaraccountInjectionConstructor=newInjectionConstructor(newIdentitySampleDbModelContext(configurationStore));container.RegisterType>(accountInjectionConstructor);container.RegisterType,RoleStore>(accountInjectionConstructor);正如来自enterpriseframework.com的这篇博文所说:首先,为ASP.NETMVCNuget包添加UnityBootstrapper。在VisualStudio“解决方案资源管理器”中>右键单击??Web项目的引用节点>单击“管理NuGet包”。从左侧菜单中选择在线>在右上角的搜索框中选择全部>在线搜索(Ctrl+E)>输入“UnitybootstrapperforASP.NETMVC”。选择“UnityBootstrapperforASP.NETMVC”并选择“安装”。安装完成后点击“关闭”然后修改your-Web-project/App_Start/UnityConfig.cs文件,更新using语句如下:usingSystem;使用System.Data.Entity;使用Microsoft.AspNet.Identity;使用Microsoft.AspNet.Identity.EntityFramework;使用Microsoft.Practices.Unity;使用Microsoft.Practices.Unity.Configuration;使用MicrosoftIdentity.Controllers;使用MicrosoftIdentity.Models;最后,在同一文件中,按如下方式更新RegisterTypes方法:publicstaticvoidRegisterTypes(IUnityContainercontainer){//注意:要从web.config加载,请取消注释以下行。确保将Microsoft.Practices.Unity.Configuration添加到using语句中。//容器.LoadConfiguration();//TODO:在此处注册您的类型container.RegisterType>();容器.RegisterType>();容器.RegisterType();容器.RegisterType();container.RegisterType(newInjectionConstructor());}HTHInstall-PackageUnity.AspNet.WebApi您的Unity需要在HttpConfiguration.DependencyResolver属性下注册。这让WebApi知道它需要使用Unity而不是反射来实现控制器。最简单的方法是使用上面的nuget包。替换AccountController中的这个属性以上就是C#学习教程:ConfigureUnityDIforASP.NETidentity分享的全部内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——publicApplicationUserManagerUserManager{返回_userManager??Request.GetOwinContext().GetUserManager();}私有集{_userManager=value;}}本文收集自网络,不代表立场,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处: