1

谢谢您的帮助!我下面的解决方案已更新为正确答案。

我有一个关于如何访问我的控制器的存储库的简单问题。如果您查看我的 addMovie 方法,我想我可以在控制器继承 IMovieRepository 之后在 ModelState.IsValid 中执行 movies.AddMovie(movie) 。

IMovie 存储库:

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);
}

电影资料库:

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>();

电影控制器:

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
}

}

4

2 回答 2

1

您需要向控制器添加一个构造函数:

private IMovieRepository _Repository;

[Inject]
public MovieController(IMovieRepository repository)
{
    _Repository = repository;
}
于 2013-03-17T18:32:11.537 回答
0
private IMovieRepository _repository;

public MoviesController(IMovieRepository repository)
{
  _repository =repository; 
}  

使用构造函数注入

于 2013-03-17T18:33:43.710 回答