どうぞ
まず、以下のように作成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
が、それは別の大きな議論になるので、ここで短くします。