---
# System prepended metadata

title: Untitled

---

``` csharp
public class UserService
{


    public int CreateNewUserProfile(string username, string password, int age, int gender, string address, DateTime birthday)
    {
    
    
        IUserRepository userRepository = new DBFactory.CreateUserRepository(Configs.UserRepositoryType);
        User user = userRepository.GetUserByUsername(username);
        if (user != null)
            return -1;
        user = new User(username, password);
        int inserCount = userRepository.Insert(user);
        if (insertCount == 0)
            return -2;
        else
        {
            MSSQLUserProfileRepository userProfileRepository = new MSSQLUserProfileRepository("connection string");
            var userProfile = Helper.Map<UserProfile>();
            UserProfile userProfile = new UserProfile();
            userProfile.UserName = username;
            userProfile.Age = age;
            userProfile.Gender = gender;
            userProfile.Address = address;
            userProfile.Birthday = birthday;
            insertCount = userProfileRepository.Insert(userProfile);
            if (insertCount == 0)
                return -3;
        }
        return 0;
    }
}

public class UserController : ApiController
{
    // API
    public bool Register(NewUserParam p)
    {
	  var result = (new UserService()).CreateNewUserProfile(p.Username, p.Password, p.Age, p.Gender, p.Address, p.Birthday);
        return result == 0;
    }
}

public interface IUserRepository
{
    User GetUserByUsername(string userName);
    int Insert(User user);
    
}

public class DBFactory
{
    public static IUserRepository CreateUserRepository(DBType type)
    {
        switch(type)
        {
        case DBType.MYSQL:
            return MYSQLUserRepository();
            break;
        case DBType.MSSQL:
            return MSSQLUserRepository();
            break;
        case DBType.Mock:
            return MockUserRepository();
            break;
        default:
            throw Exception("無法認知的類型");
        }
    }
}
 
 
public enum DBType
{
    MYSQL,
    MSSQL
}

public Class Configs
{
    public DBType UserRepositoryType {get;set;}
}


public class MockUserRepository : IUserRepository
{
    public IMock<IUserRepository> MockObj{get;set;}

    public MockUserRepository()
    {
        MockObj.SetData(a => a.GetUserByUsername<string>().Return(a => "Test GetUserByUsername").Verify();
        MockObj.SetData(a => a.Insert<User>().Return(a => "Test Insert").Verify();
    }

    public User GetUserByUsername(string userName)
    {
        return MockObj.Object.GetUserByUsername(userName);
    }
    
    public int Insert(User user)
    {
        return MockObj.Object.Insert(user);
    }
}

```