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;

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

【MVC5】使用Autofac实现依赖注入的更多相关文章

  1. NopCommerce使用Autofac实现依赖注入

    NopCommerce的依赖注入是用的AutoFac组件,这个组件在nuget可以获取,而IOC反转控制常见的实现手段之一就是DI依赖注入,而依赖注入的方式通常有:接口注入.Setter注入和构造函数 ...

  2. Autofac之依赖注入

    这里主要学习一下Autofac的依赖注入方式 默认构造函数注入 class A { public B _b; public A() { } public A(B b) { this._b = b; } ...

  3. Web API(六):使用Autofac实现依赖注入

    在这一篇文章将会讲解如何在Web API2中使用Autofac实现依赖注入. 一.创建实体类库 1.创建单独实体类 创建DI.Entity类库,用来存放所有的实体类,新建用户实体类,其结构如下: us ...

  4. NET Core源代码通过Autofac实现依赖注入

    查看.NET Core源代码通过Autofac实现依赖注入到Controller属性   阅读目录 一.前言 二.使用Autofac 三.最后 回到目录 一.前言 在之前的文章[ASP.NET Cor ...

  5. 转 Autofac怎么依赖注入ASP.NET MVC5类的静态方法

    之前我有介绍过怎么在ASP.NET mvc5中实现的Controller的依赖注入.一般是通过Contrller的构造函数的参数或者属性来注入,但是这有一个共同点就是调用这个类的方法一般都是实例方法, ...

  6. 【AutoFac】依赖注入和控制反转的使用

    在开始之前首先解释一下我认为的依赖注入和控制反转的意思.(新手理解,哪里说得不正确还请指正和见谅) 控制反转:我们向IOC容器发出获取一个对象实例的一个请求,IOC容器便把这个对象实例“注入”到我们的 ...

  7. 使用AutoFac实现依赖注入

    1.基本使用 1.1新建MVC项目并安装Autofac 注意需要安装AutoFac和AutoFac.mvc5 Install-Package Autofac Install-Package Autof ...

  8. 查看.NET Core源代码通过Autofac实现依赖注入到Controller属性

    一.前言 在之前的文章[ASP.NET Core 整合Autofac和Castle实现自动AOP拦截]中,我们讲过除了ASP.NETCore自带的IOC容器外,如何使用Autofac来接管IServi ...

  9. WebAPi使用Autofac实现依赖注入

    WebAPi依赖注入  使用记录 笔记 1.NuGet包安装 2.控制器加入构造函数 3.Global.asax  ----Application_Start 应用程序启动时 using Autofa ...

  10. Autofac 泛型依赖注入

    using Autofac;using Autofac.Extensions.DependencyInjection;using Hangfire;using Microsoft.AspNetCore ...

随机推荐

  1. 部分浏览器上a标签包裹的dom元素显示不正常

    在苹果和部分安卓机上出现,pc端和chrome浏览器响应式设计里怎么样也不会出现的访问后a标签包裹的dom元素显示不正常a标签内的hr元素颜色显示不正常hr水平线的颜色被 bootstrap的css的 ...

  2. bzoj 2159 - Crash 的 文明世界

    Description 给定一棵\(n\le 10^5\)的树, 和\(k\le 150\) 求每个点\(x\)的\[S(x) = \sum_{y=1}^n dis(x, y) ^ k\] Analy ...

  3. Unicode字符集和多字节字符集关系

      在计算机中字符通常并不是保存为图像,每个字符都是使用一个编码来表示的,而每个字符究竟使用哪个编码代表,要取决于使用哪个字符集(charset). 在最初的时候,Internet上只有一种字符集—— ...

  4. webdriver操作iframe标记的编辑器

    1.iFrame有ID 或者 name的情况//进入id="frame1"的frame中,定位id="div1"的div和id="input1&quo ...

  5. gdb 打印内存 x

    GNU gdb (Ubuntu -0ubuntu1~ Copyright (C) Free Software Foundation, Inc. License GPLv3+: GNU GPL vers ...

  6. 三、第一个cocos2d程序的代码分析

    http://blog.csdn.net/q199109106q/article/details/8591706 在第一讲中已经新建了第一个cocos2d程序,运行效果如下: 在这讲中我们来分析下里面 ...

  7. cp2102通过GPIO连接树莓派

    此博客不在更新,我的博客新地址:www.liuquanhao.com ----------------------------------------------------------------- ...

  8. 通过hover修改其他元素

    hover,我们都知道,是监听组件“悬停状态”的一个伪类. 我们一般通过hover来修改组件的背景什么的,很少涉及到太复杂的操作.也就是说我们一般只是对加了hover伪类的元素自身的样式进行改变,比如 ...

  9. slice,splice,substr,substring函数的区别

    slice: 语法:array.slice(startIndex,endIndex); 参数: startIndex:必须,规定从何处开始选取,如果为负则从尾部开始计算 : endIndex:可选,规 ...

  10. Python与正则表达式[0] -> re 模块的正则表达式匹配

    正则表达式 / Regular Expression 目录 正则表达式模式 re 模块简介 使用正则表达式进行匹配 正则表达式RE(Regular Expression, Regexp, Regex) ...