最近公司集50多号开发人员的人力围绕一个系统做开发,框架是免不了要统一的,公司提供的架构,利于分工合作,便于维护,扩展,升级,其中使用了到微软的企业库来解藕系统,只是因为框架封装,于是在网上学习了一个类似的搭建示例,贴在这里主要是为了记录与分享,希望可以帮助到一些朋友。
示例主要讲了一个根据接口反射了实体类对象的方法,而注册这种映射是写在配置文件里面的。
配置文件:
<?xml version="1.0" encoding="utf-8"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/> </configSections> <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <alias alias="IClass" type="Unity.Demo.IClass, Unity.Demo"/> <alias alias="MyClass" type="Unity.Demo.MyClass, Unity.Demo"/> <container name="First"> <register type="IClass" mapTo="MyClass"/> </container> </unity> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> </configuration>
接口文件:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Unity.Demo { public interface IClass { string ShowInfo(); } }
实现类:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Unity.Demo { public class MyClass : IClass { public string ShowInfo() { return "Hello World!"; } } }
测试页面:
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; namespace Unity.Demo { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } static IUnityContainer container = new UnityContainer(); public void InitData() { UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); container.LoadConfiguration(section, "First"); IClass classInfo = container.Resolve<IClass>(); TextBox1.Text = classInfo.ShowInfo(); } protected void Button1_Click(object sender, EventArgs e) { InitData(); } } }
以上的方法就是使用了微软企业库的unity达到了根据IClass接口名,反射了对象,取得了对象里面的实现方法效果,方便后面进行扩展和维护。
aspx文件:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Unity.Demo.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="获得信息" /> </div> </form> </body> </html>