以前没用DotNetCore之前我用spring.net。spring.net的容器在xml配置好对象然后加载容器后就可以使用。配置类型下面:
<?xml version="1.0" encoding="utf-8"?>
<objects xmlns='http://www.springframework.net' default-autowire="byType">
<!--这个配置文件主要用来配置系统的业务服务类,不要删除、修改提交其他人添加的配置,新加配置提交时主要同时提交配置使用的动态库,-->
<!--否则会造成其他人更新后报错-->
<!--检验数据访问层底层-->
<object type="LIS.DAL.Base.CacheBaseLIS,LIS.DAL.Base" singleton="false">
</object>
</objects>
到DotNetCore之后发现往容器加对象竟然是代码直接写的,而且编译才生效。类似下面:
services.AddSingleton(LIS.DAL.ORM.DBUtility.IDbFactory, LIS.DAL.Base.CacheBaseLIS);
当时就想,我去,这设计师脑子被驴踢了吗!这么写死了算什么IOC,根本没法解耦啊!
后面发现被踢的是我,不得不服设计水准。因为设计师不想把配置固化,就给你提供基础容器,你想用什么表示配置自己自由发挥,给大家留了大舞台。自己可以根据需要把接口和实现类关系配置在xml、json、txt、数据库等等。通过读取配置然后反射调用方法往容器投入。
比如我就通过反射从asmx提取配置然后注入容器,用SOAPCore发布webservice,强行模拟了DotNet时代asmx的效果。
/// <summary>
/// 通过asmx文件把wbservice对象加入IOC容器
/// <%@ WebService Language="C#" Class="LIS.BLL.WebService.LISFileService" %>
/// </summary>
/// <param name="services"></param>
public void WebServicesToIoc(IServiceCollection services)
{
//webservice文件地址
string asmxPath = Path.Combine(AppContext.BaseDirectory, LIS.Core.MultiPlatform.LISConfigurtaion.Configuration["StaticFilesPath"], "service", "asmx");
//尝试一下开发目录
if (!Directory.Exists(asmxPath))
{
DirectoryInfo di = new DirectoryInfo(AppContext.BaseDirectory);
asmxPath = Path.Combine(di.Parent.Parent.FullName, LIS.Core.MultiPlatform.LISConfigurtaion.Configuration["StaticFilesPath"], "service", "asmx");
}
if (Directory.Exists(asmxPath))
{
DirectoryInfo asmxdi = new DirectoryInfo(asmxPath);
FileInfo[] asmxFiles = asmxdi.GetFiles();
if (asmxFiles != null && asmxFiles.Length > 0)
{
foreach (FileInfo fi in asmxFiles)
{
if (fi.Extension == ".asmx")
{
string confStr = LIS.Common.TxtUtil.ReadTxt(fi.FullName);
string cFlag = "Class=\"";
int cStartIndex = confStr.IndexOf(cFlag);
int cEndIndex = confStr.IndexOf('"', cStartIndex + cFlag.Length);
string className = confStr.Substring(cStartIndex + cFlag.Length, cEndIndex - cStartIndex - cFlag.Length);
string[] classArr = className.Split('.');
string assemblyName = "";
for (int ci = 0; ci < classArr.Length - 1; ci++)
{
if (assemblyName == "")
{
assemblyName = classArr[ci];
}
else
{
assemblyName += "." + classArr[ci];
}
}
Type serviceType = LIS.DAL.ORM.DBUtility.RefectUtil.GetType(className, assemblyName);
services.AddSingleton(serviceType, serviceType);
}
}
}
}
}
他的设计思想应该就是提供最单纯的容器,一边让你注册,一边让你获取。至于你注册的类型从哪来那是你的自由。如果没能体会这个意图,就会和我开始那些,这算哪门子容器IOC,分明是强耦合啊。
一个简单可靠的容器,不用整花里胡哨的配置,提供配置了就得提供各种各样的格式支持,还把人的发挥限制死了。这就是他比spring.net的高明之处