目的
在这篇文章中,我尽量延长我在{A}解释。
我们的目标是设计一个自定义的依赖注入框架。我个人很喜欢统一框架。但我想自己做的工作。
让我们在工作。
从第I部分的持续,我做的第一步是做一些代码重构。这只是使代码有点更具可读性和效率。
,然后我继续前进,我的解决方案添加一个类库项目,并将其命名为DI。让我们只需要删除的获取与创建的类。
我谨动议Container类的直接投资项目从现有的项目。
我建立的直接投资项目和新增的XmlReader项目的引用。
现在我的解决方案看起来如下:{S0}
容器类如下所示:using System;
using System.Xml;
using System.Reflection;
namespace DI
{
public static class Container
{
public static Type CreateInstance()
{
var reader = new XmlTextReader
(@"C:\Mahadesh\Blogs\SimpleDI\XMLReader\XML\Sample.xml");
var assem = Assembly.GetCallingAssembly();
while (reader.Read())
if (reader.NodeType == XmlNodeType.Element)
{
Type type = null;
while (reader.MoveToNextAttribute()) // Read attributes
if (reader.Name == "Name")
{
type = assem.GetType(reader.Value); // typeName is a string
}
return type;
}
reader.Close();
Console.ReadLine();
return null;
}
}
}
可以看出,这阵子我用的时间:
这是因为我想从另一个类的程序集的XML访问。我们不能移动到另一个组件的XML,因为XML是用户配置的一部分,应始终驻留在客户端上。 GetCallingAssembly()将负载从该呼叫正在组装,这在我们的例子是XmlReader。
好了,这是差不多了。
有没有改变类中的XmlReader大会... ...我刚才从计划中的XmlReader大会类中删除不必要的报表。
Program类中的XMLReader的代码看起来如下:using System;
using DI;
namespace XMLReader
{
class Program
{
static void Main(string[] args)
{
var obj = Activator.CreateInstance( Container.CreateInstance());
var m = Container.CreateInstance().GetMethod("SampleMethod");
m.Invoke(obj, new Object[] { 42 });
Console.ReadLine();
}
}
}
最后,让我们运行我们的XMLReader项目。