建立Spring.NET IoC容器(簡單工廠)需要NuGet添加Spring.Core程式包。
using Spring.Context;
using Spring.Context.Support;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Spring.Net.IOC.Factory
{
public class SpringNetIocHelper
{
public static T GetService<T>(string serviceName)
{
IApplicationContext ctx = ContextRegistry.GetContext();
return (T)ctx.GetObject(serviceName);
}
}
}
Spring.NET IoC容器主要是通過配置檔案來擷取對象并實作依賴注入,簡單配置如下:
應用程式配置檔案
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiclRnblN2XjlGcjAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHL3FlaONTSE9UNNpHW4Z0MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL2QzNxETOyMjM2IDOwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
可以将Service配置從應用程式配置檔案搬到Config/service.config檔案中
測試代碼
測試代碼連結