感谢您的帮助!我的解决方案已更新为正确的答案。
我有一个关于如何访问控制器存储库的简单问题。如果你看看我的addMovie方法,我想我可以在控制器继承IMovieRepository之后在ModelState.IsValid中做movie.AddMovie(movie)。
IMovieRepository:
public interface IMovieRepository : IDisposable
{
IEnumerable<Movies> GetMovies();
Movies GetMovieByID(int id);
void AddMovie(Movies movie);
void UpdateMovie(Movies movie);
void DeleteMovie(int id);
void save(Movies movie);
}
MovieRepository:
public class MovieRepository : BaseRepository, IMovieRepository
{
private MovieContext db;
public MovieRepository(MovieContext repo)
{
db = repo;
}
public IEnumerable<Movies> GetMovies()
{
return db.Movies.ToList();
}
public Movies GetMovieByID(int id)
{
return db.Movies.Find(id);
}
public void AddMovie(Movies movie)
{
db.Movies.Add(movie);
}
public void UpdateMovie(Movies movie)
{
db.Entry(movie).State = EntityState.Modified;
}
public void DeleteMovie(int id)
{
Movies movie = db.Movies.Find(id);
db.Movies.Remove(movie);
}
public void save(Movies movie)
{
if (movie.movieID == 0)
db.Movies.Add(movie);
else
db.Entry<Movies>(movie).State = System.Data.EntityState.Modified;
db.SaveChanges();
}
}
NinjectDependencyResolve:
Bind<IMovieRepository>().To<MovieRepository>();
MoviesController:
public class MoviesController : Controller
{
private IMovieRepository movieRepository;
public MoviesController()
{
this.movieRepository = new MovieRepository(new MovieContext());
}
public MoviesController(IMovieRepository movieRepository)
{
this.movieRepository = movieRepository;
}
#region "GET"
//
// GET: /Admin/Movies/
public ActionResult Index()
{
return View();
}
#endregion
#region "POST"
[HttpPost]
public ActionResult addMovie(Movies movie)
{
if (ModelState.IsValid)
{
movieRepository.AddMovie(movie);
movieRepository.save(movie);
return RedirectToAction("index", "movies");
}
return View(movie);
}
#endregion
}
}
答案 0 :(得分:1)
您需要向控制器添加构造函数:
private IMovieRepository _Repository;
[Inject]
public MovieController(IMovieRepository repository)
{
_Repository = repository;
}
答案 1 :(得分:0)
private IMovieRepository _repository;
public MoviesController(IMovieRepository repository)
{
_repository =repository;
}
使用构造函数注入