解决方法
你可以有一个存储库:
public interface IUsersRepository { public User GetUser(int id); }
然后实现它:
public class UsersRepository: IUsersRepository { private readonly string _connectionString; public UsersRepository(string connectionString) { _connectionString = connectionString; } public User GetUser(int id) { // Here you are free to do whatever data access code you like // You can invoke direct sql queries,stored procedures,whatever using (var conn = new sqlConnection(_connectionString)) using (var cmd = conn.CreateCommand()) { conn.open(); cmd.CommandText = "SELECT id,name FROM users WHERE id = @id"; cmd.Parameters.AddWithValue("@id",id); using (var reader = cmd.ExecuteReader()) { if (!reader.Read()) { return null; } return new User { Id = reader.GetInt32(reader.Getordinal("id")),Name = reader.GetString(reader.Getordinal("name")),} } } } }
然后您的控制器可以使用此存储库:
public class UsersController: Controller { private readonly IUsersRepository _repository; public UsersController(IUsersRepository repository) { _repository = repository; } public ActionResult Index(int id) { var model = _repository.GetUser(id); return View(model); } }
这样控制器不再依赖于数据访问层的实现:无论您是使用纯ADO.NET,NHibernate,EF还是其他一些ORM,调用外部Web服务,XML,都是您的名字。
现在剩下的就是配置你最喜欢的DI框架,注入到控制器的存储库的正确实现。如果明天你决定改变你的数据访问技术,没有问题,只需写一个不同的IUsersRepository接口的实现,并重新配置你的DI框架使用它。无需触摸控制器逻辑。
您的MVC应用程序不再与数据存储的方式相关联。这使得更容易单独测试您的控制器,因为它们不再紧密耦合到特定的数据源。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。