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

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

转载于:https://www.cnblogs.com/Ryukaka/p/mvc5_dependency_injection_autofac.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值