Asp.Net MVC 之 Autofac 初步使用2 集成mvc 属性注入以及自动注入
首先看下Demo2的结构
分享下demo源码 :http://pan.baidu.com/s/1qYtZCrM
然后下面一步步将Autofac集成到mvc中。
首先,定义Model Product.cs
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public string Remark { get; set; }
public DateTime Date { get; set; }
}
Product.cs
第二步 创建文件夹IRepository 用于存放仓储接口IProductRepository
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
bool Update(Product item);
bool Delete(int id);
}
IProductRepository.cs
第三步 创建文件夹Repository 定义ProductRepository 实现IProductRepository仓储接口
public class ProductRepository : IProductRepository
{
private List<Product> Products = new List<Product>(); public ProductRepository()
{
Add(new Product { Id = , Name = "手机", Price = , Remark = "4g 手机", Date = DateTime.Now.AddDays(-) });
Add(new Product { Id = , Name = "电脑", Price = , Remark = "笔记本本", Date = DateTime.Now.AddDays(-) });
Add(new Product { Id = , Name = "bb机", Price = , Remark = "大时代必备", Date = DateTime.Now.AddDays(-) });
Add(new Product { Id = , Name = "pad", Price = , Remark = "mini 电脑", Date = DateTime.Now });
}
public IEnumerable<Product> GetAll()
{
return Products;
} public Product Get(int id)
{
return Products.Find(p => p.Id == id);
} public Product Add(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
Products.Add(item);
return item;
} public bool Update(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
int index = Products.FindIndex(p => p.Id == item.Id);
if (index == -)
{
return false;
}
Products.RemoveAt(index);
Products.Add(item);
return true;
} public bool Delete(int id)
{
Products.RemoveAll(p => p.Id == id);
return true;
}
}
ProductRepository.cs
ok,WebApplication_AutoFac引用AutoFac_Demo2 以及从VS中的NuGet来加载Autofac.Integration.Mvc
下一步定义ProductController 这里我们用构造器注入
public class ProductController : Controller
{
readonly IProductRepository repository;
//构造器注入
public ProductController(IProductRepository repository)
{
this.repository = repository;
}
// GET: /Product/
public ActionResult Index()
{
var data = repository.GetAll();
return View(data);
}
}
ProductController.cs
index页也比较简单,用vs根据model生成的list页
@model IEnumerable<AutoFac_Demo2.Model.Product>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.Remark)
</th>
<th>
@Html.DisplayNameFor(model => model.Date)
</th>
<th></th>
</tr> @foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Remark)
</td>
<td>
@Html.DisplayFor(modelItem => item.Date)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
} </table>
Index.cshtml
最后最关键的实现注入
protected void Application_Start()
{
//创建autofac管理注册类的容器实例
var builder = new ContainerBuilder();
//下面就需要为这个容器注册它可以管理的类型
//builder的Register方法可以通过多种方式注册类型,之前在demo1里面也演示了好几种方式了。
builder.RegisterType<ProductRepository>().As<IProductRepository>();
//使用Autofac提供的RegisterControllers扩展方法来对程序集中所有的Controller一次性的完成注册
builder.RegisterControllers(Assembly.GetExecutingAssembly());//生成具体的实例
var container = builder.Build();
//下面就是使用MVC的扩展 更改了MVC中的注入方式.
DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
其实除了构造函数注入还可以属性注入 把之前repository 改为get set 就变成属性了
public class ProductController : Controller
{
#region
//readonly IProductRepository repository;
////构造器注入
//public ProductController(IProductRepository repository)
//{
// this.repository = repository;
//}
#endregion
public IProductRepository repository { get; set; }
// GET: /Product/
public ActionResult Index()
{
var data = repository.GetAll();
return View(data);
}
}
然后,将
//使用Autofac提供的RegisterControllers扩展方法来对程序集中所有的Controller一次性的完成注册
builder.RegisterControllers(Assembly.GetExecutingAssembly());
改为
builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); // 这样支持属性注入
最后效果:
最后的最后,为了不像 builder.RegisterType<ProductRepository>().As<IProductRepository>(); 这样一个一个的注册,所以要像装载controller一样完成自动注入
自动注入
Autofac提供一个RegisterAssemblyTypes方法。它会去扫描所有的dll并把每个类注册为它所实现的接口。既然能够自动注入,那么接口和类的定义一定要有一定的规律。我们可以定义IDependency接口的类型,其他任何的接口都需要继承这个接口。
public interface IDependency
{
}
public interface IProductRepository : IDependency
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
bool Update(Product item);
bool Delete(int id);
}
添加IUserRepository.cs 继承IDependency
public interface IUserRepository : IDependency
{
IEnumerable<User> GetAll();
User Get(int id);
User Add(User item);
bool Update(User item);
bool Delete(int id);
}
IUserRepository.cs
仓储实现
public class UserRepository : IUserRepository
{
private List<User> Users = new List<User>();
public UserRepository()
{
Add(new User { Id = , Name = "hyh" });
Add(new User { Id = , Name = "hyg" });
Add(new User { Id = , Name = "hyr" });
} public IEnumerable<User> GetAll()
{
return Users;
} public User Get(int id)
{
return Users.Find(p => p.Id == id);
} public User Add(User item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
Users.Add(item);
return item;
} public bool Update(User item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
int index = Users.FindIndex(p => p.Id == item.Id);
if (index == -)
{
return false;
}
Users.RemoveAt(index);
Users.Add(item);
return true;
} public bool Delete(int id)
{
Users.RemoveAll(p => p.Id == id);
return true;
}
}
UserRepository.cs
最后Global
#region 自动注入
//创建autofac管理注册类的容器实例
var builder = new ContainerBuilder();
Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();
//注册所有实现了 IDependency 接口的类型
Type baseType = typeof(IDependency);
builder.RegisterAssemblyTypes(assemblies)
.Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
.AsSelf().AsImplementedInterfaces()
.PropertiesAutowired().InstancePerLifetimeScope(); //注册MVC类型
builder.RegisterControllers(assemblies).PropertiesAutowired();
builder.RegisterFilterProvider();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
#endregion
结果如下:
ok,先到这了...
Asp.Net MVC 之 Autofac 初步使用2 集成mvc 属性注入以及自动注入的更多相关文章
- Asp.Net MVC 之 Autofac 初步使用3 集成web api
今天我们试着在WebApi2实现autofac的注入,关于这方面也是看了几位园友的分享省了不少时间,所以结合着前篇的demo再新建webapi进行... 一样开篇还是发下大概demo结构: 还是nug ...
- Autofac手动注入及自动注入示例
参考:http://www.cnblogs.com/xinchuang/archive/2013/05/07/3065433.html#2911661 一.环境 vs2012.mvc4..Net Fr ...
- Asp.Net MVC 之 Autofac 初步使用1
Autofac是.NET领域最为流行的IOC框架之一,传说是速度最快的一个: 优点: 它是C#语言联系很紧密,也就是说C#里的很多编程方式都可以为Autofac使用 较低的学习曲线,学习它非常的简单, ...
- ASP.NET IOC之 AutoFac的认识和结合MVC的使用
这几天研究了解发现AutoFac是个牛X的IOC容器,是.NET领域比较流行的IOC框架之一,传说是速度最快的,~ 据相关资料,相关学习,和认知,遂做了一些整理 优点: 它是C#语言联系很紧密,也就是 ...
- Autofac容器使用属性进行WebApi自动注入
背景 使用Autofac进行依赖注入时,经常遇到的场景是在容器中进行类似如下代码的注入操作: builder.RegisterType<BackInStockSubscriptionServic ...
- MVC中Autofac的使用
参考博文 https://www.cnblogs.com/liupeng/p/4806184.html https://blog.csdn.net/qq_37214567/article/detail ...
- Asp.Net Mvc使用Autofac实现依赖注入
在asp.net mvc控制器中使用Autofac来解析依赖 如下Controller中使用构造函数依赖注入接口IPeople : public class AutoFacController : C ...
- ADO.NET .net core2.0添加json文件并转化成类注入控制器使用 简单了解 iTextSharp实现HTML to PDF ASP.NET MVC 中 Autofac依赖注入DI 控制反转IOC 了解一下 C# AutoMapper 了解一下
ADO.NET 一.ADO.NET概要 ADO.NET是.NET框架中的重要组件,主要用于完成C#应用程序访问数据库 二.ADO.NET的组成 ①System.Data → DataTable, ...
- ASP.NET Core Web 应用程序系列(三)- 在ASP.NET Core中使用Autofac替换自带DI进行构造函数和属性的批量依赖注入(MVC当中应用)
在上一章中主要和大家分享了在ASP.NET Core中如何使用Autofac替换自带DI进行构造函数的批量依赖注入,本章将和大家继续分享如何使之能够同时支持属性的批量依赖注入. 约定: 1.仓储层接口 ...
随机推荐
- php短数组写法
在php 5.4+的版本中,可以使用 [] 来表示 array() 例子: // On PHP 5.1 $data = array("foo", "bar" ...
- HTML/CSS/Javascript调试入门(转)
推荐Chrome作为开发工具(FF可以使用FireBug,IE8和之后的版本也有自己的调试工具) 1.HTML的调试 将鼠标放在任意元素上,右键Inspect Element,即可查看该元素的HTML ...
- 【BZOJ 3926】【ZJOI 2015】诸神眷顾的幻想乡
http://www.lydsy.com/JudgeOnline/problem.php?id=3926 广义后缀自动机的例题,感觉广义后缀自动机好恶心... 广义后缀自动机是对一个trie建立的后缀 ...
- 按钮(Buton)组价的功能和用法
Button继承了TextView,它主要是在UI界面上生成一个按钮,该按钮可以供用户单机,当用户单击按钮时,按钮会触发一个onClick事件. 按钮使用起来比较容易,可以通过为按钮指定android ...
- javascript获取整数随机数
javascript获取整数随机数 // 从4到10的随机数,|0是生成正整数 var numBars = Math.random()*6+4|0; 也可以通过右移0位(或者左移0位)进行取整 var ...
- 将SWF文件用作资源打包
使用Flash开发网页游戏少不了与各种美术资源打交道.对于静态资源的那就是各种图片,对于会动的资源可以考虑直接做成swf.制作成swf的美术资源又可以分为两种:一种是直接将关键帧罗列在主时间轴上,那么 ...
- yii2 中布局文件的 设置方法
网页主题应用的属性: [yii\base\Application::layout|layout 该属性指定渲染 视图 默认使用的布局名字,默认值为 'main' 对应布局路径下的 main.php 文 ...
- ArcGIS API for JavaScript 4.2学习笔记[4] 第二章其余感兴趣的例子
先马克,估计要用到的有: 视图存档 2D地图添加指南针 视图移动 鹰眼 2D3D视图同步.同视图不同数据同步 以后实战的时候再仔细研究研究.
- [Bullet3]创建世界(场景)及常见函数
创建世界(场景)及常见函数 官方文档:http://bulletphysics.org 开源代码:https://github.com/bulletphysics/bullet3/releases A ...
- 分布式搜索之搭建Solrcloud(Solr集群)
Solrcloud介绍: SolrCloud(solr集群)是Solr提供的分布式搜索方案. 当你需要大规模,容错,分布式索引和检索能力时使用SolrCloud. 当索引量很大,搜索请求并发很高时,同 ...