0

私はこのコードを実行するための最良の方法を見つけようとしています (私のやり方は良くないと思うので): 私は問題を理解しやすいようにしようとしました.

public ActionResult Index()
{
var user=new User();
user.load(1);
return View(user);
}

load(int id )
{
//pseudocode:
//1. load user from repository1     
//2. load address from repository2
//3.load payments from repository3
}
4

1 に答える 1

0

どうぞ

まず、以下のように作成UserModelServiceします

public class UserModelService
{
    public User Load(int id)
    {
        var userRepository = new UserRepository();
        var user = userRepository.Load(id);

        var addressRepository = new AddressRepository();
        user.Address = addressRepository.LoadForUserId(id);
        return user;
    }
}

次に、コントローラーの元のコードを次のように変更します

public ActionResult Index()
{
    var userModelSerice =new UserModelService();
    var user = userModelService.load(1);
    return View(user);
}

上記の残りのコードリファレンスはすべて以下のとおりです

public class AddressRepository
{
    public Address LoadForUserId(int id)
    {
        // Load the address for given user id
    }
}

public class UserRepository
{
    public User Load(int id)
    {
        // Load and return user
    }
}

public class User
{
    public Address Address { get; set; }
}

public class Address
{
}

これで、コントローラーアクションで、の新しいインスタンスを作成する代わりに、UserModelServiceコンストラクターを介してそれを挿入することができます。同様の原則を適用してリポジトリを注入することもできますUserModelServiceが、それは別の大きな議論になるので、ここで短くします。

于 2012-11-11T17:50:42.517 に答える