在构造函数中使用此运算符初始化对象
本文关键字:运算符 初始化 对象 构造函数 | 更新日期: 2023-09-27 18:30:46
当我尝试使用 MVC 中的存储库模式实现代码优先方法时,我遇到了以下一些困难:
我有一个接口,其中声明了以下几个方法:
public interface IRepository
{
User Getuserdetail(int UserId);
void Save(User Obj);
void delete(int Userid);
void update(User user);
}
然后我有一个存储库类,它可以使用上面的接口来定义所有方法,并将创建一个单独的实体框架层:
public class Repository : IRepository
{
RepoDBContext _context;
Repository(RepoDBContext Context)
{
this._context = Context;
}
public User Getuserdetail(int Userid)
{
var user = _context.User.Where(m => m.id == Userid).FirstOrDefault();
return user;
}
public void Save(User user)
{
_context.User.Add(user);
_context.SaveChanges();
}
}
现在你能检查一下这个类的构造函数吗?此构造函数初始化的变量是"RepoDBContext"类型,它用于分配它的引用类型也是"RepoDBContext"。它的内部表现是否如下所示?
RepoDBContext _context=new RepoDBContext();
我的RepoDBContext类如下:
public class RepoDBContext : DbContext
{
public DbSet<User> User { get; set; }
}
此外,如果是正确的执行方式,那么我将如何在控制器中调用此类才能通过用户界面执行某些功能。请指导相同的内容,请不要介意我的英语。谢谢
我想你已经在评论和奥斯卡和柯克的回答中does assigning a parameter to a field is equivalent to instantiating a new instance of that type
状态的问题有了答案。
但我只想更进一步,尝试回答你的另一个问题:how will I have to call this class in my controller to do some functionality over my user interface.
.
如果使用存储库模式创建结构,则不希望控制器处理 DbContext 类的实例,因为如果这样做,那么拥有单独的存储库层有什么好处?我看到人们使用并且我自己在几个应用程序中使用它的常见模式如下:
IUserRepository
public interface IUserRepository
{
User GetUserDetail(int userId);
void Save(User user);
void Delete(int userId);
void Update(User user);
}
用户存储库
public class UserRepository : IUserRepository
{
public User GetUserDetail(int userId)
{
using(var _context = new RepoDBContext())
{
return _context.User.Where(m => m.id == userId).FirstOrDefault();
}
}
//other implementations here..
}
然后,创建另一个层,该层将成为您的业务层,类似于存储库。
IUserBusiness
public interface IUserBusiness
{
User GetUserDetail(int userId);
void Save(User user);
void Delete(int userId);
void Update(User user);
}
用户业务
public class UserBusiness : IUserBusiness
{
private readonly IUserRepository userRepository;
//CTOR receives a Repository instance via DI
public UserBusiness(IUserRepository userRepository)
{
this.userBusiness = userBusiness;
}
public User GetUserDetail(int userId)
{
//Call repository to get User details
return this.userRepository.GetUserDetail(userId);
}
//other implementations here
}
用户控制器(示例)
public class UserController : Controller
{
private readonly IUserBusiness userBusiness;
//Controller receives a UserBusinnes instance via DI
public UserController(IUserBusiness userBusiness)
{
this.userBusiness = userBusiness;
}
public ActionResult GetDetail(int userId)
{
//Call your "repository" to get user data
var userDetail = userBusiness.GetUserDetail(userId);
//more logic here
}
}
看到区别了吗?应用程序的每一层都与一件事有关。您将数据控制器发送到业务层,业务层可能会应用一些业务规则或验证,最后调用知道如何与数据库或其他存储通信的存储库层。您的控制器不关心如何创建数据库类的实例或进行查询。它只是接收请求,请求数据并返回给调用方。
不,将 RepoDBContext 的现有实例分配给变量与调用 new RepoDBContext()
不同。赋值只是赋值,不会分配新对象。
题外话:另请注意,C# 编码准则建议方法参数应命名为 likeThis
(即,使用首字母小写字母)。这将使你的代码与其他 .Net 代码库更加一致。