1

我有一个登录控制器,它接受用户实例,并在登录方法中正确调用验证用户,但如果我以类似方式包含构造函数,则问题出现在 UserManager

    public LoginController(IUser user)
    {
        this.user = user;
    }
    [httpPost]
    public ActionResult Login(UserLogin model)
    {
        if (ModelState.IsValid)
        {
           // var userMgr = new UserManager();

            if (user.ValidateUser(model.UserName, model.Password))
            {

                  return RedirectToAction("Index", "Home");

            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is        incorrect.");
            }
            // return View("UserLogin");
        }

以下是问题出现的地方

 public class UserManager : IUser 
 {

     IUser _user;

    public UserManager(IUser user)
   {
      _user=user;
   }

   public void displayUser()
   {
      //.......
     //.....    

   }

  public void somefunction()
 {
    _user.displayUser();
 }

}

我使用 UserManager() 构造函数的原因是因为我想使用 _user.displayUser()

我在 global.aspx 中进行了如下配置

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        var container = Container.InitContainer();

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
     }

和 Container.InitContainer() 调用以下类

       public static class Container
       {
         public static IUnityContainer InitContainer()
         {

            var container = new UnityContainer();
          // Register the relevant types for the         

          // container here through classes or configuration    

          //container.RegisterType<IUser, UserManager>(new                         ContainerControlledLifetimeManager());

        container.RegisterType<IUser, UserManager>(new ContainerControlledLifetimeManager());



        return container;

    } 

我有 UnityDepdendency 解析器类,如下所示

   public class UnityDependencyResolver : IDependencyResolver
   {
        private IUnityContainer _container;

      #region Ctor

      public UnityDependencyResolver(IUnityContainer container)
      {

          _container = container;

      }



    #endregion

    public object GetService(Type serviceType)
    {
        try
        {

            return _container.Resolve(serviceType);

        }

        catch (Exception ex)
        {

            return null;

        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {

            return _container.ResolveAll(serviceType);

        }

        catch (Exception ex)
        {

            return new List<object>();

        }
    }
} 
4

1 回答 1

1

我们可以用this.displayUser();

UserManager userobj=new UserManager() 不需要

于 2013-03-20T10:57:49.903 回答