代码之家  ›  专栏  ›  技术社区  ›  Jamie Dixon

只有静态方法的模型有意义吗?

  •  2
  • Jamie Dixon  · 技术社区  · 16 年前

    我有一个ASP.NETMVC2项目,我正在工作,我想知道我应该把一些代码放在哪里。

    这些方法包括: UserExistsInDatabase UserIsRegisteredForActivity , GetUserIdFromFacebookId 等等等等。

    这些方法应该在UsersModel类中,还是更适合模型上下文之外的user helper类?

    4 回复  |  直到 16 年前
        1
  •  5
  •   Darin Dimitrov    16 年前

    不要使用静态方法。将它们抽象到存储库中:

    public interface IUsersRepository
    {
        bool UserExistsInDatabase(User user);
        bool UserIsRegisteredForActivity(User user);
        ...
    }
    

    然后针对某些数据存储实施:

    public class UsersRepository : IUsersRepository
    {
        ...
    }
    

    public class HomeController : Controller
    {
        private readonly IUsersRepository _repository;
        public HomeController(IUsersRepository repository)
        {
            // the repository is injected into the controller by the DI framework
            _repository = repository;
        }
    
        // ... some action methods that will use the repository
    }
    
        2
  •  1
  •   Amitabh    16 年前

    我认为我们应该避免使用静态方法,因为它在模拟中会有问题。这些方法更适合UserRespository/UserService类。

        3
  •  0
  •   OlimilOops    16 年前


    *现有数据库,
    *已注册活动,
    *GetIdFromFacebookId

        4
  •  0
  •   Brian Mains    16 年前

    这两个选项都可以。或者,您可以将它们定义为扩展方法,并将它们直接附加到用户类。