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. php 内核变量 引用计数器写时复制

    写时复制,是一个解决内存复用的方法,就是你在php语言层,如$d=$c=$b=$a='value';把$a赋给另一个或多个变量,这时这个变量都只占用一个内存块,当其中一个变量值改变时,才会开辟另一个内 ...

  2. Android消息推送解决方案

    前言 消息推送在Android开发中应用的场景是越来越多了,比如说电商产品进行活动宣传.资讯类产品进行新闻推送等等,如下图: 推送消息截图 本文将介绍Android中实现消息推送的7种主流解决方案 目 ...

  3. poj 3071 Football (概率DP水题)

    G - Football Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u Submit ...

  4. panel(NOIP模拟赛Round 4)

    好吧,,这道题..本来以为挺难的.打了个暴力bfs+hash(期望得分30,实际得分30) 奇特的是,这道题如果不用hash(期望得分20,实际得分100),好吧数据实在是太水了(不会T吗?) 然后我 ...

  5. [leetcode]Convert Sorted Array to Binary Search Tre

    排好序的... 中间是root , root左边是left,root右边是right 递归建树. /** * Definition for binary tree * struct TreeNode ...

  6. Linux/Android——input_handler之evdev (四) 【转】

    转自:http://blog.csdn.net/u013491946/article/details/72638919 版权声明:免责声明: 本人在此发文(包括但不限于汉字.拼音.拉丁字母)均为随意敲 ...

  7. mtk GPIO口

    http://blog.csdn.net/mcgrady_tracy/article/details/39320691 mt6582多达168个GPIO口,当然这些GPIO口是复用的,注意lk和Lin ...

  8. Request的Body只能读取一次解决方法

    一.需要一个类继承HttpServletRequestWrapper,该类继承了ServletRequestWrapper并实现了HttpServletRequest, 因此它可作为request在F ...

  9. postman的使用(转载)

    Postman介绍 Postman是google开发的一款功能强大的网页调试与发送网页HTTP请求,并能运行测试用例的的Chrome插件.其主要功能包括: 模拟各种HTTP requests 从常用的 ...

  10. Xamarin for Visual Studio 3.11.590 稳定版 破解补丁 Version 3

    前提概要 全新安装请参考 安装 Xamarin for Visual Studio. Release Log 3.11.590 此版本是紧急修复(HotFix)版,重点改善了 build-tool 及 ...