【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;


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实现依赖注入的更多相关文章
- NopCommerce使用Autofac实现依赖注入
NopCommerce的依赖注入是用的AutoFac组件,这个组件在nuget可以获取,而IOC反转控制常见的实现手段之一就是DI依赖注入,而依赖注入的方式通常有:接口注入.Setter注入和构造函数 ...
- Autofac之依赖注入
这里主要学习一下Autofac的依赖注入方式 默认构造函数注入 class A { public B _b; public A() { } public A(B b) { this._b = b; } ...
- Web API(六):使用Autofac实现依赖注入
在这一篇文章将会讲解如何在Web API2中使用Autofac实现依赖注入. 一.创建实体类库 1.创建单独实体类 创建DI.Entity类库,用来存放所有的实体类,新建用户实体类,其结构如下: us ...
- NET Core源代码通过Autofac实现依赖注入
查看.NET Core源代码通过Autofac实现依赖注入到Controller属性 阅读目录 一.前言 二.使用Autofac 三.最后 回到目录 一.前言 在之前的文章[ASP.NET Cor ...
- 转 Autofac怎么依赖注入ASP.NET MVC5类的静态方法
之前我有介绍过怎么在ASP.NET mvc5中实现的Controller的依赖注入.一般是通过Contrller的构造函数的参数或者属性来注入,但是这有一个共同点就是调用这个类的方法一般都是实例方法, ...
- 【AutoFac】依赖注入和控制反转的使用
在开始之前首先解释一下我认为的依赖注入和控制反转的意思.(新手理解,哪里说得不正确还请指正和见谅) 控制反转:我们向IOC容器发出获取一个对象实例的一个请求,IOC容器便把这个对象实例“注入”到我们的 ...
- 使用AutoFac实现依赖注入
1.基本使用 1.1新建MVC项目并安装Autofac 注意需要安装AutoFac和AutoFac.mvc5 Install-Package Autofac Install-Package Autof ...
- 查看.NET Core源代码通过Autofac实现依赖注入到Controller属性
一.前言 在之前的文章[ASP.NET Core 整合Autofac和Castle实现自动AOP拦截]中,我们讲过除了ASP.NETCore自带的IOC容器外,如何使用Autofac来接管IServi ...
- WebAPi使用Autofac实现依赖注入
WebAPi依赖注入 使用记录 笔记 1.NuGet包安装 2.控制器加入构造函数 3.Global.asax ----Application_Start 应用程序启动时 using Autofa ...
- Autofac 泛型依赖注入
using Autofac;using Autofac.Extensions.DependencyInjection;using Hangfire;using Microsoft.AspNetCore ...
随机推荐
- Linux系统调用--getrlimit()与setrlimit()函数详解【转】
转自:http://www.cnblogs.com/niocai/archive/2012/04/01/2428128.html 功能描述:获取或设定资源使用限制.每种资源都有相关的软硬限制,软限制是 ...
- bootstrapValidator 版本差异问题导致的submitHandler失效问题
我用过的两个版本: v0.5.2-dev,0.4.5 这里针对于提交方法进行说明一下,如下代码: <script> $(function () { $("#addUserForm ...
- appium+python自动化26-模拟手势点击坐标(tap)【转载】
# 前言:有时候定位元素的时候,你使出了十八班武艺还是定位不到,怎么办呢?(面试经常会问)那就拿出绝招:点元素所在位置的坐标 tap用法 1.tap是模拟手指点击,一般页面上元素的语法有两个参数,第 ...
- 配置OpenResty支持SSL(不受信任的证书)
#关闭防火墙 chkconfig iptables off service iptables stop #关闭SELINUX sed -i 's/SELINUX=enforcing/SELINUX=d ...
- Mac下安装npm,http-server,安装虚拟服务器
http-server是一个简单的,不需要配置的命令行下使用的http服务器.类似的还有Xampp等. 针对前端开发工程的代码不需要编译的特点,使用这种简单的服务器十分的便利. 1.安装这个首先要安装 ...
- AC日记——[国家集训队2011]旅游(宋方睿) cogs 1867
[国家集训队2011]旅游(宋方睿) 思路: 树链剖分,边权转点权: 线段树维护三个东西,sum,max,min: 当一个区间变成相反数时,sum=-sum,max=-min,min=-max: 来, ...
- 计蒜客 28319.Interesting Integers-类似斐波那契数列-递推思维题 (Benelux Algorithm Programming Contest 2014 Final ACM-ICPC Asia Training League 暑假第一阶段第二场 I)
I. Interesting Integers 传送门 应该是叫思维题吧,反正敲一下脑壳才知道自己哪里写错了.要敢于暴力. 这个题的题意就是给你一个数,让你逆推出递推的最开始的两个数(假设一开始的两个 ...
- ACM阶段总结(2016.10.07-2016.11.09)
来这里也有一段时间了…… 总感觉自己练得不是很有效. 最近的一些行动就是不断做比赛,然后不停地补,但是感觉这样像只无头苍蝇,没有效果,学不到什么真正的东西. 最近开始打算补专题,做做codeforce ...
- Python的程序结构[6] -> 迭代器/Iterator -> 迭代器浅析
迭代器 / Iteratior 目录 可迭代对象与迭代器协议 迭代器 迭代器(模拟)的建立 1 可迭代对象与迭代器协议 对于迭代器首先需要了解两个定义,迭代器协议 (Iterator Protocol ...
- 用fiddler测试移动端翻页
大家在移动端是怎么测试翻页的,肯定都是下拉或上滑吧,我也是这样测试的 但如果你要验证数据是否与pc端数据一致时,可能是第一页,第二页看看,或最后几页数据看看,在pc端看简单,直接点击最后一页就行,在移 ...