在默认MVC中使用unity的依赖注入会破坏登录

本文关键字:注入 依赖 登录 unity MVC 默认 | 更新日期: 2023-09-27 18:15:42

我正在编写一个web应用程序,我使用默认的微软MVC网站作为起点。在此之后,我使用实体框架创建了一个食谱数据库,用于我的web应用程序,并编写了一个存储库和一些业务层方法。然后我使用Unity的依赖注入来消除它们之间的耦合。我将这些代码放在global.asax.cs.

中的mvapplication类中。
private IUnityContainer Container;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            ConfigureObjects();

        }
        private void ConfigureObjects()
        {
            Container = new UnityContainer();
            Container.RegisterType<IRecipeRequest, BasicRecipeRequest>();
            Container.RegisterType<IRecipeRepository, RecipeRepositoryEntityFramework>();
            Container.RegisterType<IRecipeContext, RecipeContext>();
            DependencyResolver.SetResolver(new UnityDependencyResolver(Container));
        } 

属于我的只是与依赖注入相关的那些位。

执行此操作后,使用任何与用户登录相关的页面都会返回错误,例如注册,登录。它将返回标题如下的错误:

The current type, Microsoft.AspNet.Identity.IUserStore`1[UKHO.Recipes.Www.Models.ApplicationUser], is an interface and cannot be constructed. Are you missing a type mapping? 

查看使用诊断工具在visual studio中抛出的异常,我得到了这个:

"An error occurred when trying to create a controller of type 'UKHO.WeeklyRecipes.Www.Controllers.AccountController'. Make sure that the controller has a parameterless public constructor."

accountscontroller是一个由deafult创建的控制器,我还没有碰过它,它包含一个无参数构造函数和另一个构造函数。它们是这样的:

   public AccountController()
            {
            }

   public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
            {
                UserManager = userManager;
                SignInManager = signInManager;
            }

通过将[InjectionConstructor()]放在无参数构造函数的前面,错误就消失了。在我看来,Unity试图解决ApplicationUserManager和ApplicationSignInManager,即使我没有注册这些类型,并且把[InjectionConstructor()]使Unity看到空构造函数,所以什么也不做。我主要想知道为什么会发生这种情况,因为我的印象是unity应该只干扰你注册的类型。也欢迎黄油解决方案。

编辑:这也发生当你想改变一个帐户设置,而是与ManageContoler错误,这也可以通过把[InjectionConstructor()]在空构造函数前解决。

在默认MVC中使用unity的依赖注入会破坏登录

您只配置了以下对象的依赖关系:

Container.RegisterType<IRecipeRequest, BasicRecipeRequest>();
            Container.RegisterType<IRecipeRepository, RecipeRepositoryEntityFramework>();
            Container.RegisterType<IRecipeContext, RecipeContext>();

但是在你的控制器上,你有两个没有配置的依赖项,ApplicationUserManager和ApplicationSignInManager。

Unity不知道这些依赖关系,所以它不能在构造函数上注入,从而试图调用无参数的构造函数。

如果你在控制器上有一个带参数的构造函数,unity将查找它并尝试解析所有依赖项,无论你配置了哪个。