Spring.jpg
? Spring.Net 為建立企業(yè)級應(yīng)用提供了一套輕量級的解決方案问潭。通過Spring.NET,我們可以用統(tǒng)一且透明的方式來配置應(yīng)用程序。Spring.NET的重點是為中間層提供聲明式事務(wù)管理,以及一個功能齊全的ASP.NET擴展框架永罚。Spring.NET是非侵入式的,代碼對框架本身不會產(chǎn)生任何依賴.
? Spring.Net 就是抽象工廠模式 , 它使用配置文件的方式,去是實現(xiàn)了控制反轉(zhuǎn), 控制反轉(zhuǎn)就是通過依賴注入的方式是對象A不需要使用new對象B, 而是通過容器的方式,將對象B注入到對象A的應(yīng)用.
通過簡單的例子來介紹Spring.Net簡單的使用:
第一步 : 先新建一個控制臺程序;
第二步 : 引入Spring.Net文件,可用在NuGet中搜索,下載.也可以在官網(wǎng)中下載并在項目引用相關(guān).dll文件;
第三步 : 接下來就是創(chuàng)建相關(guān)的類文件
using System;
namespace SpringdotNetDemo {
public class Service1 {
public string Name { get; set; }
public Service2 Service { get; set; }
public void Show() {
Service.Show();
Console.WriteLine("Spring.Net:" + Name);
}
}
}
using System;
namespace SpringdotNetDemo {
public class Service2 {
public void Show() {
Console.WriteLine("Service2");
}
}
}
第四步 : 在App.Config中配置Spring.Net
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!--Spring.Net節(jié)點配置-->
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<!--Spring.Net 配置-->
<spring>
<context>
<!--容器配置-->
<resource uri="config://spring/objects"/>
<!--可以將objects節(jié)點的配置保存在xml文件卧秘,更改文件更改屬性呢袱,復制到輸出目錄:始終復制-->
<!--<resource uri="file://objects.xml"/>-->
</context>
<objects xmlns="http://www.springframework.net">
<!--這里放容器里面的所有節(jié)點-->
<description>An example that demonstrates simple IoC features.</description>
<!--name 必須要唯一的,type=類的全名稱翅敌,所在的程序集-->
<object name="Service1" type="SpringdotNetDemo.Serive1, SpringdotNetDemo">
<!--設(shè)置Service1中屬性的值-->
<property name="Name" value="Service1.Name"/>
<property name="Service" ref="Service2"/>
</object>
<object name="Service2" type="SpringdotNetDemo.Serive2, SpringdotNetDemo"></object>
</objects>
</spring>
</configuration>
第五步 : 在主函數(shù)中應(yīng)用配置:
using Spring.Context;
using Spring.Context.Support;
using System;
namespace SpringdotNetDemo {
class Program {
static void Main(string[] args) {
//Spring.Net 創(chuàng)建實例的方式轉(zhuǎn)為容器幫我們創(chuàng)建
//創(chuàng)建spring容器上下文
IApplicationContext context = ContextRegistry.GetContext();
//通過容器創(chuàng)建對象
var ser = context.GetObject("Service1") as Service1;
ser.Show();
Console.ReadKey();
}
}
}
其運行結(jié)果:
Result.jpg
以上就是Spring.Net的簡單應(yīng)用