autoFac:最流行的依赖注入和IOC框架,轻量且高性能,对项目代码几乎无任何侵入性
Spring.NET:依赖注入、面向方面编程(AOP)、数据访问抽象、以及ASP.NET集成。
autoFac:
1 /// <summary>
/// 属性注入
/// </summary>
public IPeople people { get; set; }
public ActionResult Index()
{
var data = people.GetAll();
return View();
}
2
public class AutofacConfig
{
public static void Register()
{
//实例化控制器
var builder = new ContainerBuilder();
//注册类型(映射实现类)
builder.RegisterType<People>().As<IPeople>();
//注册到控制器
builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
var container = builder.Build();
//下面就是使用MVC的扩展 更改了MVC中的注入方式.
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
3 global文件中加入:
AutofacConfig.Register();
Spring.NET:
1
public IHello Hello333 { get; set; }
public string name2 { get; set; }
public ActionResult Index()
{
ViewBag.Message = Hello333.SayHelloWorld()+ name2;
return View();
}
2
Global 继承修改SpringMvcApplication
public class MvcApplication : SpringMvcApplication
{
}
3 webConfig配置
<configuration>
<configSections>
<!--必须放在configSections的第一个位置-->
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc5" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="/Configs/Spring.xml" />
</context>
</spring>
Spring.xml:
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
<!--这里放容器里面的所有节点-->
<description>An example that demonstrates simple IoC features.</description>
<!--//type属性值必须是包含程序集名称在内的类型全名 "命名空间,程序集"-->
<object id="Hello" type="SpringDemo.demo.Hello, SpringDemo"/>
<!--对象默认配置是单例的,Controller不是单例的,所以这里把singleton设置为false -->
<object type="SpringDemo.Controllers.HomeController, SpringDemo" singleton="false">
<property name="Hello333" ref="Hello"/>
<property name="name2" value="张三"/>
</object>
</objects>