代码改变世界

【MVC5】使用Autofac实现依赖注入

2015-11-05 18:10  佳佳的博客  阅读(1156)  评论(0编辑  收藏  举报

1.安装Autofac

在Package Manager Console执行如下命令:

Install-Package Autofac
Install-Package Autofac.Mvc5

2.追加Model(Models.Movie)

using System.Data.Entity;

namespace FirstDenpendencyInjection.Models
{
    public class Movie
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public int ReleaseYear { get; set; }
        public int RunTime { get; set; }
    }

    public class MovieDb : DbContext
    {
        public DbSet<Movie> Movies { get; set; }
    }
}

3.追加Controller和View

右键Controllers目录,Add Controller;

image

image

4.追加Repository的接口和类

IMovieRepository(Repositories.Inaterface)

using FirstDenpendencyInjection.Models;
using System.Collections.Generic;

namespace FirstDenpendencyInjection.Repositories.Inaterface
{
    public interface IMovieRepository
    {
        List<Movie> GetMovies();

        Movie GetMovie(int id);

        int Insert(Movie movie);

        int Update(Movie movie);

        int Delete(int id);
    }
}

MovieRepository(Repositories)

using FirstDenpendencyInjection.Models;
using FirstDenpendencyInjection.Repositories.Inaterface;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace FirstDenpendencyInjection.Repositories
{
    public class MovieRepository : IMovieRepository
    {

        private MovieDb db = new MovieDb();

        public int Delete(int id)
        {
            Movie movie = db.Movies.Find(id);
            db.Movies.Remove(movie);
            return db.SaveChanges();
        }

        public Movie GetMovie(int id)
        {
            return db.Movies.Find(id);
        }

        public List<Movie> GetMovies()
        {
            return db.Movies.ToList();
        }

        public int Insert(Movie movie)
        {
            db.Movies.Add(movie);
            return db.SaveChanges();
        }

        public int Update(Movie movie)
        {
            db.Entry(movie).State = EntityState.Modified;
            return db.SaveChanges();
        }
    }
}

5.修改MoviesController类

using FirstDenpendencyInjection.Models;
using FirstDenpendencyInjection.Repositories.Inaterface;
using System.Net;
using System.Web.Mvc;

namespace FirstDenpendencyInjection.Controllers
{
    public class MoviesController : Controller
    {
        //private MovieDb db = new MovieDb();

        private IMovieRepository _repository;

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

        // GET: Movies
        public ActionResult Index()
        {
            return View(_repository.GetMovies());
        }

        // GET: Movies/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = _repository.GetMovie(id.Value);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }

        // GET: Movies/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Movies/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Title,ReleaseYear,RunTime")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                _repository.Insert(movie);
                //db.Movies.Add(movie);
                //db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(movie);
        }

        // GET: Movies/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = _repository.GetMovie(id.Value);// db.Movies.Find(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }

        // POST: Movies/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Title,ReleaseYear,RunTime")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                _repository.Update(movie);
                //db.Entry(movie).State = EntityState.Modified;
                //db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(movie);
        }

        // GET: Movies/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = _repository.GetMovie(id.Value);// db.Movies.Find(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }

        // POST: Movies/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            _repository.Delete(id);
            //Movie movie = db.Movies.Find(id);
            //db.Movies.Remove(movie);
            //db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            //if (disposing)
            //{
            //    db.Dispose();
            //}
            base.Dispose(disposing);
        }
    }
}

6.注册组件(Global.asax)

using Autofac;
using Autofac.Integration.Mvc;
using FirstDenpendencyInjection.Controllers;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace FirstDenpendencyInjection
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // 注册组件
            var assembly = Assembly.GetExecutingAssembly();
            var builder = new ContainerBuilder();

            // 注册单个实例
            //builder.RegisterInstance(new MovieRepository()).As<IMovieRepository>();
            builder.RegisterType<MoviesController>();

            // 扫描assembly中的组件(类名以Repository结尾)
            builder.RegisterAssemblyTypes(assembly)
                   .Where(t => t.Name.EndsWith("Repository"))
                   .AsImplementedInterfaces();

            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}