autofac初识
在开始autofac时,有必要先了解两个关键词:“控制反转(IoC/Inverse Of Control)”与“依赖注入(DI/Dependence injection)”。
控制反转(IoC):它把传统上由程序代码直接操控的对象的调用权交给容器,通过容器来实现对象组件的装配和管理。
依赖注入(DI):就是由IoC容器在运行期间,动态地将某种依赖关系注入到对象之中。
public class BMW
{
/// <summary>
///
/// </summary>
/// <param name="series">车系</param>
public void Create(string series)
{
Console.WriteLine("生产了宝马" + series);
}
} public class Porsche
{
/// <summary>
///
/// </summary>
/// <param name="series">车系</param>
public void Create(string series)
{
Console.WriteLine("生产了宝时捷" + series);
}
}
上面定义了宝马与保时捷两个类,它们都有Create方法,参数车系,传统的调用方式如下:
BMW bmw = new BMW();
bmw.Create("730Li");
Porsche porsche = new Porsche();
porsche.Create("卡宴");
这里我们看到,需要使用new创建实例并调用方法
改进,使用工厂方式
public interface ICarCreator
{
void Create(string series);
} public class BMW : ICarCreator
{
/// <summary>
///
/// </summary>
/// <param name="series">车系</param>
public void Create(string series)
{
Console.WriteLine("生产了宝马" + series);
}
} public class Porsche : ICarCreator
{
/// <summary>
///
/// </summary>
/// <param name="series">车系</param>
public void Create(string series)
{
Console.WriteLine("生产了宝时捷" + series);
}
}
调用方式,这里使用了反射的形式,在配置文件里配置(类似支持多个数据库的操作工厂)
ICarCreator car = (ICarCreator)Assembly.GetExecutingAssembly().CreateInstance(ConfigurationManager.AppSettings["Brand"]); //使用了反射方式
car.Create("suv");
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Brand" value="AutofacDemo1.BMW"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
进一步改进,使用autofac,将创建实例交给autofac
var builder = new ContainerBuilder(); builder.RegisterType<ICarCreator>();
builder.RegisterType<BMW>().As<ICarCreator>();
//builder.RegisterType<Porsche>().As<ICarCreator>();
Container = builder.Build();
using (var scope = Container.BeginLifetimeScope())
{
var writer = scope.Resolve<ICarCreator>();
writer.Create("轿车");
}
完整的代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using Autofac; namespace AutofacDemo1
{
class Program
{
private static IContainer Container { get; set; }
static void Main(string[] args)
{
#region 普通的调用
//BMW bmw = new BMW();
//bmw.Create("730Li");
//Porsche porsche = new Porsche();
//porsche.Create("卡宴");
#endregion #region 工厂的方式
//ICarCreator car = (ICarCreator)Assembly.GetExecutingAssembly().CreateInstance(ConfigurationManager.AppSettings["Brand"]); //使用了反射方式
//car.Create("suv");
#endregion #region 使用Ioc[Autofac]
var builder = new ContainerBuilder(); builder.RegisterType<ICarCreator>();
builder.RegisterType<BMW>().As<ICarCreator>();
//builder.RegisterType<Porsche>().As<ICarCreator>();
Container = builder.Build();
using (var scope = Container.BeginLifetimeScope())
{
var writer = scope.Resolve<ICarCreator>();
writer.Create("轿车");
}
#endregion Console.ReadKey();
}
} public interface ICarCreator
{
void Create(string series);
} public class BMW : ICarCreator
{
/// <summary>
///
/// </summary>
/// <param name="series">车系</param>
public void Create(string series)
{
Console.WriteLine("生产了宝马" + series);
}
} public class Porsche : ICarCreator
{
/// <summary>
///
/// </summary>
/// <param name="series">车系</param>
public void Create(string series)
{
Console.WriteLine("生产了宝时捷" + series);
}
}
}
autofac初识的更多相关文章
- Autofac 框架初识与应用
文字首发地址 一.前言 这上一篇中,主要讲述了什么是IoC容器,以及了解到它是DI构造函注入的框架,它管理着依赖项的生命周期以及映射关系,同时也介绍实践了在ASP.Net Core中,默认提供的内置I ...
- ASP.NET Core2使用Autofac实现IOC依赖注入竟然能如此的优雅简便
初识ASP.NET Core的小伙伴一定会发现,其几乎所有的项目依赖都是通过依赖注入方式进行链式串通的.这是因为其使用了依赖注入 (DI) 的软件设计模式,代码的设计是遵循着“高内聚.低耦合”的原则, ...
- ASP.NET Core2使用Autofac实现IOC依赖注入竟然能如此的优雅简便(转载)
原文地址:https://www.cnblogs.com/Andre/p/9604759.html 初识ASP.NET Core的小伙伴一定会发现,其几乎所有的项目依赖都是通过依赖注入方式进行链式串通 ...
- AutoFac在项目中的应用
技能大全:http://www.cnblogs.com/dunitian/p/4822808.html#skill 完整Demo:https://github.com/dunitian/LoTCode ...
- Autofac - MVC/WebApi中的应用
Autofac前面写了那么多篇, 其实就是为了今天这一篇, Autofac在MVC和WebApi中的应用. 一.目录结构 先看一下我的目录结构吧, 搭了个非常简单的架构, IOC(web), IBLL ...
- Autofac - 生命周期
实例生命周期决定在同一个服务的每个请求的实例是如何共享的. 当请求一个服务的时候,Autofac会返回一个单例 (single instance作用域), 一个新的对象 (per lifetime作用 ...
- Autofac - 属性注入
属性注入不同于通过构造函数方式传入参数. 这里是通过注入的方式, 在类创建完毕之后, 资源释放之前, 给属性赋值. 这里, 我重新弄一些类来演示这一篇吧. public class ClassA { ...
- Autofac 的点滴
泛型类型的注册和使用 public interface IRepository<T> where T:class { } public interface ISchoolDetailRep ...
- Android动画效果之初识Property Animation(属性动画)
前言: 前面两篇介绍了Android的Tween Animation(补间动画) Android动画效果之Tween Animation(补间动画).Frame Animation(逐帧动画)Andr ...
随机推荐
- thinkphp5的mkdir() Permission denied问题
最近一直在用tp5写项目,在此遇到的问题也比较多.今天来谈谈“mkdir() Permission denied”错误. 你如果不仅仅写代码,还得部署到线上,那么这个tp5的这个错误,你有很大概率会遇 ...
- [Swift实际操作]七、常见概念-(8)日历Calendar和时区TimerZone
本文将为你演示日历的一些属性,以及如何利用日历,查询是否为昨天.今天和明天. 首先引入需要用到的界面工具框架 import UIKit 然后生成一个日历对象,并获得用户当前的日历. var calen ...
- windows系统正常但linux系统下找不到文件的问题
问题描述:最近一个项目开发环境是windows系统,正式环境是linux系统.验证码图片在开发环境正常,但是在正式环境下一直报404. 问题原因:File dir = new File(realPat ...
- 使用python+selenium对web进行自动化测试
想用python代码,对web网页进行自动化测试 web自动化测试和手动测试的区别: 手动测试:通过手动去对网页的功能进行点点点 web自动化:可以通过代码,自动对网页点点点 首先,将python+s ...
- 使用js栈stack类的实现
使用js栈stack类的实现 /*使用栈stack类的实现*/ function stack() { this.dataStore = [];//保存栈内元素,初始化为一个空数组 this.top = ...
- CentOS7 配置 Redis Sentinel主从集群配置
Redis Sentinel主从集群 环境.准备 slave配置 sentinel配置 测试 C#连接Redis Sentinel 1.环境.准备 单实例3台CentOS7服务器,IP地址.: 192 ...
- Mina的服务器
(一) package testMina; import java.io.IOException; import java.net.InetSocketAddress; import java.nio ...
- vue制作小程序--mpvue
mpvue是一个使用 Vue.js 开发小程序的前端框架 http://mpvue.com/ sass的使用 https://segmentfault.com/q/1010000014194954 n ...
- C/C++ -- Gui编程 -- Qt库的使用 -- Qt5总结
主要变化: 1.与Qt4相比,Qt5可以直接显示中文不需要手工转码2.Qt5模块发生变化,大部分组件并入widgets模块 注意事项:工程文件加一句greaterThan(QT_MAJOR_VERSI ...
- udgrade rubygems-update
gem install rubygems-update update_rubygems gem update --system gem install rubygems-bundler