1. 程式人生 > >IOC框架-autoFac、Spring.NET

IOC框架-autoFac、Spring.NET

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>