Ioc依赖注入的使用DEMO

时间:2022-11-07 20:21:33

本文使用的是Autofac 3.0.2的版本

前提是项目引用Autofac.dll和Autofac.Configuration,并添加一个packages.config (注明使用framework版本)

<?xml version="1.0" encoding="utf-8" ?>
<packages>
<package id="Autofac" version="3.0.2" targetFramework="net40" />
</packages>

1,首先申明类,接口和实现适配器 (DEMO是一个简单的XML数据加载到XLS中转换成HTML)

using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace WebServiceTestApp
{
//接口实现
public class XmlToXls : IXmlToXls
{
//转换核心方法
private string MergeXmlWithXslt(string xlstFile, string xmlFile)
{
string html = "";

try
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(@xlstFile);

XPathDocument doc = new XPathDocument(xmlFile);
using (MemoryStream writer = new MemoryStream())
{
XmlWriter xmlwriter = XmlWriter.Create(writer, xslt.OutputSettings);
xslt.Transform(doc, xmlwriter);

byte[] buffer = writer.GetBuffer();
html = System.Text.Encoding.UTF8.GetString(buffer);
writer.Close();
}

return html;
}
catch
{
return "";
}
}

private string MergeXmlStringWithXslt(string xlstFile, string xmlString)
{
string html = "";

try
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(@xlstFile);

using (StringReader reader = new StringReader(xmlString))
{
XPathDocument doc = new XPathDocument(reader);
using (MemoryStream writer = new MemoryStream())
{
XmlWriter xmlwriter = XmlWriter.Create(writer, xslt.OutputSettings);
xslt.Transform(doc, xmlwriter);

byte[] buffer = writer.GetBuffer();
html = System.Text.Encoding.UTF8.GetString(buffer);
writer.Close();
}
}

return html;
}
catch
{
return "";
}
}

private string EncodeBase64(string code)
{
string encode = "";
try
{
byte[] bytearray = System.Text.Encoding.GetEncoding(0).GetBytes(code);
encode = Convert.ToBase64String(bytearray);
}
catch
{
encode = code;
}

return encode;
}

private string DecodeBase64(string code)
{
string decode = "";
try
{
byte[] bytes = Convert.FromBase64String(code);
decode = System.Text.Encoding.GetEncoding(0).GetString(bytes);
}
catch
{
decode = code;
}

return decode;
}

//根据xsl和xml转换成html
public string BuildHtmlFromXmlAndXsl(string xslFileName, string xmlFileName, bool clearReturn = true)
{
string html = "";
string fullPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, @"Xslt\" + xslFileName);
string xmlPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, @"Xslt\" + xmlFileName);

html = MergeXmlWithXslt(fullPath, xmlPath);
if (html != "")
{
if (clearReturn)
html = html.Replace("\r\n", "");
html = html.Replace(" <", "<");
html = html.Replace(" <", "<");
html = html.Replace(" <", "<");
html = "<" + html.Substring(2, html.Length - 2);
}

return html;
}

public string BuildHtmlFromXmlStringAndXsl(string xslFileName, string xmlString, bool clearReturn = true)
{
string html = "";
string fullPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, @"Xslt\" + xslFileName);

html = MergeXmlStringWithXslt(fullPath, xmlString);
if (html != "")
{
if (clearReturn)
html = html.Replace("\r\n", "");
html = html.Replace(" <", "<");
html = html.Replace(" <", "<");
html = html.Replace(" <", "<");
html = "<" + html.Substring(2, html.Length - 2);
}

return html;
}

//从xml中读取内容
public string GetStringFromXmlFile(string xmlFileName)
{
string xmlPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, @"Xslt\" + xmlFileName);
XmlDocument doc = new XmlDocument();
using (XmlReader reader = XmlReader.Create(xmlPath))
{
doc.Load(reader);
}

return doc.InnerXml;
}
}

//声明接口
public interface IXmlToXls
{
string GetStringFromXmlFile(string xmlFileName);
string BuildHtmlFromXmlAndXsl(string xslFileName, string xmlFileName, bool clearReturn = true);
string BuildHtmlFromXmlStringAndXsl(string xslFileName, string xmlString, bool clearReturn = true);
}

//实现的适配器
public class XmlToXlsLister
{
private readonly IXmlToXls iXmlToXls;
public XmlToXlsLister(IXmlToXls iXmlToXls)
{
this.iXmlToXls = iXmlToXls;
}

//简单统一处理
public string BuildHtml(string xslFileName, string xmlFileName, string xmlString)
{
if (!string.IsNullOrEmpty(xmlFileName))
return iXmlToXls.BuildHtmlFromXmlAndXsl(xslFileName, xmlFileName);
if (!string.IsNullOrEmpty(xmlString))
return iXmlToXls.BuildHtmlFromXmlStringAndXsl(xslFileName, xmlString);

return string.Empty;
}
}
}

2.继续实现一个Autofac的操作类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autofac;

namespace WebServiceTestApp
{
public class AutofacContainer
{
public static IContainer Container { get; set; }

public static void BuildContainer()
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<XmlToXls>();

builder.RegisterType<XmlToXls>().AsImplementedInterfaces();
builder.RegisterType<XmlToXlsLister>();

Container = builder.Build();
}

public static T Resolve<T>() where T : class
{
return Container.Resolve<T>();
}

public static object Resolve(Type type)
{
return Container.Resolve(type);
}
}
}


3.使用上述的类,在构造或load中

            //Ioc 依赖注入
AutofacContainer.BuildContainer();
xml = AutofacContainer.Resolve<XmlToXls>();
lister = AutofacContainer.Resolve<XmlToXlsLister>();

具体操作

        private XmlToXls xml;
private XmlToXlsLister lister;

private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = xml.GetStringFromXmlFile("cdcatalog.xml");
webBrowser1.DocumentText = lister.BuildHtml("cdcatalog.xsl", "cdcatalog.xml", "");
}

private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = txt;
webBrowser1.DocumentText = lister.BuildHtml("cdcatalog.xsl", "", textBox1.Text);
}


注:xml和xls文件可以参考 http://www.w3school.com.cn/xsl/xsl_transformation.asp