-
C#教程之C#教程之autofac 用法总结
本站最新发布 C#从入门到精通
试听地址 https://www.xin3721.com/eschool/CSharpxin3721/
试听地址 https://www.xin3721.com/eschool/CSharpxin3721/
autofac官网:
http://autofaccn.readthedocs.io/en/latest/getting-started/index.html
autofac作为一个热门ioc框架,还是有了解一下的必要的。这里用两个小案例来简单说说autofac在.net framework控制台应用程序和asp.net mvc5 项目中的使用。
先从控制台应用程序开始。
首先nuget安装autofac,新建IDemo接口
namespace AutuFacDemo { interface IDemo { string Hello(); } }
新建Demo类实现IDemo接口:
namespace AutuFacDemo { public class Demo :IDemo { public string Hello() { return "hello"; } } }
Program.cs:
using Autofac; using System; namespace AutuFacDemo { class Program { private static IContainer Container { set; get; } static void Main(string[] args) { var builder = new ContainerBuilder(); builder.RegisterType<Demo>().As<IDemo>(); Container = builder.Build(); using (var scope = Container.BeginLifetimeScope()) { var demo = scope.Resolve<IDemo>(); Console.WriteLine(demo.Hello()); Console.ReadKey(); } } } }
这样就完成了一个最简单的控制台Demo。
现在开始使用mvc5案例。
nuget安装Autofac.Mvc5
同一解决方案内新建IBLL和BLL类库,IBLL存放IDemo.cs:
namespace IBLL { public interface IDemo { string Hello(); } }
BLL存放Demo.cs
using IBLL; namespace BLL { public class Demo :IDemo { public string Hello() { return "hello"; } } }
Global.asax.cs配置autofac:
using Autofac; using Autofac.Integration.Mvc; using BLL; using IBLL; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace WebDemo { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(WebApiApplication).Assembly); builder.RegisterType<Demo>().As<IDemo>(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }
控制器配置Demo方法:
using IBLL; using System.Web.Mvc; namespace WebDemo.Controllers { public class HomeController : Controller { private IDemo _demo; public HomeController(IDemo demo) { this._demo = demo; } public ActionResult Index() { ViewBag.Title = "Home Page"; return View(); } public ActionResult Demo() { string hello = _demo.Hello(); return Content(hello); } } }
运行后访问Demo方法,即可看到效果。
栏目列表
最新更新
如何使用OS模块中的stat方法
Python os 模块
seek() 方法
python打开文件实例1
Python写入文件
什么是流?
文件操作如何进制逐行读取
Python相对路径
with创建临时运行环境
Python文件操作
.Net Standard(.Net Core)实现获取配置信息
Linux PXE + Kickstart 自动装机
Shell 编程 基础
Shell 编程 条件语句
CentOS8-网卡配置及详解
Linux中LVM逻辑卷管理
1.数码相框-相框框架分析(1)
Ubuntu armhf 版本国内源
Linux中raid磁盘阵列
搭建简易网站
access教程之Access简介
mysql 安装了最新版本8.x版本后的报错:
Mysql空间数据&空间索引(spatial)
如何远程连接SQL Server数据库的图文教程
复制SqlServer数据库的方法
搜索sql语句
sql中返回参数的值
sql中生成查询的模糊匹配字符串
数据定义功能
数据操作功能