C# Ioc 接口注册实例以及注入MVC Controller
当弄一个小程序时,就忽略了使用Ioc这种手段,作为一个帅气程序员,代码规范,你懂的~,废话不多说,快速搭建一个Ioc接口实例以及直接注入到 MVC Controller 构造函数中如下:
MVC integration requires the Autofac.Mvc5 NuGet package.
文档:http://docs.autofac.org/en/latest/integration/mvc.html#register-controllers
代码如下:
1.首先我们创建一个WebContainer.cs 类文件,代码如下:
using System.Web;
using System.Web.Mvc;
using Autofac;
using Autofac.Core;
using Autofac.Integration.Mvc; namespace Dlw.MiddleService.Ioc
{
public class WebContainer
{
internal static IContainer Container { get; set; }
public static void Initialize(IModule webComponentsModule)
{
var builder = new ContainerBuilder(); builder.RegisterModule(webComponentsModule);
builder.RegisterModule<AutofacWebTypesModule>();
Container = builder.Build();
DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(Container)); }
public static T Resolve<T>()
{
// In case of a background thread, the DependencyResolver will not be able to find
// the appropriate lifetime, which will result in an error. That's why we fallback to the root container.
// Requesting a type that has been configured to use a "Per Request" lifetime scope, will result in a error
// in case of a background thread if (HttpContext.Current == null)
return Container.Resolve<T>(); return DependencyResolver.Current.GetService<T>();
}
}
}
对于Resolve静态方法,用于Controller 之外的地方,用起来很方便。
2.创建一个IocConfig.cs 类文件,规范一点把这个文件创建在App_Start folder下,此类继承Autofac的Model,代码如下:
using Autofac;
using System.Reflection;
using Autofac.Integration.Mvc;
using Dlw.MiddleService.Sap.Interface; using Module = Autofac.Module; namespace Dlw.MiddleService.App_Start
{
public class IocConfig : Module
{
protected override void Load(ContainerBuilder builder)
{
// Register the mvc controllers.
builder.RegisterControllers(Assembly.GetExecutingAssembly());
// Register all interface
builder.RegisterAssemblyTypes(typeof(IStore).Assembly)
.Where(t => typeof(IStore).IsAssignableFrom(t))
.AsImplementedInterfaces().SingleInstance();
}
}
}
3.创建父类接口,Ioc注册接口的入口
public interface IStore
{
}
}
4.创建接口且继承Ioc注册入口 IStore,
public interface IRepository : IStore
{
string Test();
}
5.接口实现
public class RepositoryImpl : IRepository
{
public string Test()
{
return "Hello World";
}
}
6. 在程序集中初始化Ioc且启动它进行工作
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
WebContainer.Initialize(new IocConfig());
}
}
7. MVC Controller 注入
public class HomeController : Controller
{
public IRepository _store;
public HomeController(IRepository store)
{
_store = store;
}
// GET: Home
public ActionResult Index()
{
var result = _store.Test();
return Content(result);
}
}
去吧少年,Ioc接口实例和MVC Controller 参数注入已经完成,Good Luck~
C# Ioc 接口注册实例以及注入MVC Controller的更多相关文章
- 面向接口可扩展框架之“Mvc扩展框架及DI”
面向接口可扩展框架之“Mvc扩展框架及DI” 标题“Mvc扩展框架及DI”有点绕口,我也想不出好的命名,因为这个内容很杂,涉及多个模块,但在日常开发又密不可分 首先说Mvc扩展框架,该Mvc扩展就是把 ...
- Git使用总结 Asp.net生命周期与Http协议 托管代码与非托管代码的区别 通过IEnumerable接口遍历数据 依赖注入与控制反转 C#多线程——优先级 AutoFac容器初步 C#特性详解 C#特性详解 WPF 可触摸移动的ScrollViewer控件 .NET(C#)能开发出什么样的APP?盘点那些通过Smobiler开发的移动应用
一,原理 首先,我们要明白Git是什么,它是一个管理工具或软件,用来管理什么的呢?当然是在软件开发过程中管理软件或者文件的不同版本的工具,一些作家也可以用这个管理自己创作的文本文件,由Linus开发的 ...
- ASP.NET Core中使用IOC三部曲(二.采用Autofac来替换IOC容器,并实现属性注入)
前言 本文主要是详解一下在ASP.NET Core中,自带的IOC容器相关的使用方式和注入类型的生命周期. 这里就不详细的赘述IOC是什么 以及DI是什么了.. emm..不懂的可以自行百度. 目录 ...
- Spring IOC(三)依赖注入
本系列目录: Spring IOC(一)概览 Spring IOC(二)容器初始化 Spring IOC(三)依赖注入 Spring IOC(四)总结 目录 1.AbstractBeanFactory ...
- Spring IoC是如何进行依赖注入的
依赖注入(DI) DI(Dependency Injection),Spring IoC 不是一种技术,而是一种思想,通过这种思想,能够指导我们设计出松耦合的程序代码.而Spring IoC这个思想的 ...
- Spring的IOC控制反转和依赖注入-重点-spring核心之一
IoC:Inverse of Control(控制反转): 读作"反转控制",更好理解,不是什么技术,而是一种设计思想,好比于MVC.就是将原本在程序中手动创建对象的控制权,交由S ...
- Spring专题2: DI,IOC 控制反转和依赖注入
合集目录 Spring专题2: DI,IOC 控制反转和依赖注入 https://docs.spring.io/spring/docs/2.5.x/reference/aop.html https:/ ...
- Spring 04: IOC控制反转 + DI依赖注入
Spring中的IOC 一种思想,两种实现方式 IOC (Inversion of Control):控制反转,是一种概念和思想,指由Spring容器完成对象创建和依赖注入 核心业务:(a)对象的创建 ...
- MyBatis-Spring中间件逻辑分析(怎么把Mapper接口注册到Spring中)
1. 文档介绍 1.1. 为什么要写这个文档 接触Spring和MyBatis也挺久的了,但是一直还停留在使用的层面上,导致很多时候光知道怎么用,而不知道其具体原理,这样就很难做一 ...
随机推荐
- 学习笔记 - 兼容ie的透明度问题
.opacity{font-size: 14px;-khtml-opacity:0.6;-moz-opacity:0.6;filter:alpha(opacity=60);filter:"a ...
- Codeforces 768A Oath of the Night's Watch
A. Oath of the Night's Watch time limit per test:2 seconds memory limit per test:256 megabytes input ...
- 让两个数x,y一直保持互质的模版
int gcd(int x,int y) { )return x; else return gcd(y,x%y); }
- BZOJ:4031: [HEOI2015]小Z的房间
Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 1103 Solved: 536[Submit][Status][Discuss] Descripti ...
- angular2 路由
路由是个模块,命令行生成:ng generate module routerTest; 自己组建: 路由模块说明: Routes:路由配置,路由配置文件类型.比如:const routing:Rout ...
- 试用最强Spark IDE--IDEA
1.安装IntelliJ IDEA IDEA 全称 IntelliJ IDEA,是java语言开发的集成环境,IntelliJ在业界被公认为最好的java开发工具之一,尤其在智能代码助手.代码自动提示 ...
- 1.移植3.4内核-分析内核启动过程,重新分区,烧写jffs2文件系统
1.在上章-移植uboot里.我们来分析下uboot是如何进入到内核的 首先,uboot启动内核是通过bootcmd命令行实现的,在我们之前移植的bootcmd命令行如下所示: bootcmd=nan ...
- ThinkPHP3.2 实现Mysql数据库备份
<?php header("Content-type:text/html;charset=utf-8"); //配置信息 $cfg_dbhost = 'localhost'; ...
- win7彻底卸载iis
https://jingyan.baidu.com/article/e5c39bf5829e8e39d660336c.html 昨天在电脑上搭建了PHP开发环境之后,重启apache服务器老是报错,检 ...
- win7、win10进程pid4占用80端口的解决办法
https://jingyan.baidu.com/article/7e4409533ffe092fc1e2ef10.html 今天想用wamp架设服务器,但是程序启动不起来,查看系统端口,80端口被 ...