应用wCF 企业库搭建的一个Demo

小弟最近因项目需要自己搭建框架,但是不知道怎么搭建,所以做了一个搭建的demo,希望大家能之处其中不妥的地方,项目是传统的bussess项目,基本的信息维护。

项目的整体机构图

应用wCF 企业库搭建的一个Demo_第1张图片

1 首先我们来说说数据层


namespace Neower.UnicomVideo.DataAccess
{
    public class UserInfoDA : DataAccessBase
    {
        public virtual UserInfo[] GetUserInfos()
        {
            string sql = "SELECT * FROM dbo.UserInfo";
            DbCommand command = Db.GetSqlStringCommand(sql);
            DataSet ds = Db.ExecuteDataSet(command);

            List<UserInfo> userInfos = new List<UserInfo>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                UserInfo userInfo = new UserInfo()
                {
                    UserID = row["UserID"].ToString(),
                    UserName = row["UserName"].ToString(),
                    UserAge = string.IsNullOrEmpty(row["UserAge"].ToString()) ? new  Nullable<int>() : int.Parse(row["UserAge"].ToString())
                };
                userInfos.Add(userInfo);
            }
            return userInfos.ToArray();
        }
    }
}

 

基类代码 

public class DataAccessBase { private Database _db; /// <summary> /// Default constructor /// </summary> public DataAccessBase() { // Create the Database object, using the default database service. // The default database service is determined through configuration. _db = DatabaseFactory.CreateDatabase(); } /// <summary> /// Open and returns a connection /// </summary> /// <returns>Returns DbConnection containing the opened connection</returns> public IDbConnection GetConnection() { IDbConnection connection = _db.CreateConnection(); connection.Open(); return connection; } /// <summary> /// Close and dispose of a connection /// </summary> /// <param name="connection">The DbConnection object to be close</param> public void CloseConnection(IDbConnection connection) { if (connection != null) { connection.Close(); connection.Dispose(); } } /// <summary> /// Get the database object /// </summary> protected Database Db { get { return _db; } } }

在这层有一个帮助类 主要用于创建对象,因为后面的每一层都要访问数据层,所以把它放到数据层了

public partial class Helper { static IUnityContainer container = new UnityContainer(); static Helper() { UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); container.LoadConfiguration(section, "DataType"); } public static T GetInstance<T>() { return container.Resolve<T>(); } // Fields }

2紧接下来的就是组建层 也是我们常说的业务管理层

 namespace Neower.UnicomVideo.BusinessComponent
{
    public class UserInfoBC
    {
        UserInfoDA da;

        public UserInfoBC(UserInfoDA userinfoDA)
        {
            da = userinfoDA;
        }
        public virtual UserInfo[] GetUserInfos()
        {
            return da.GetUserInfos();
        }
    }
}

3 接口层 wcf的接口我们放到单独的一个项目中

 namespace Neower.UnicomVideo.Common
{
    [ServiceContract]
    public interface IUserInfo
    {
        [OperationContract]
        [FaultContract(typeof(FaultException))]
        UserInfo[] GetUserInfos();
    }
}

4 外观层 即使wcf接口的实现层

 namespace Neower.UnicomVideo.BusinessFacade
{
    public class UserInfoBF : IUserInfo
    {
        UserInfoBC bc;
        public UserInfoBF()
        {
            bc = Helper.GetInstance<UserInfoBC>();
        }

        public UserInfo[] GetUserInfos()
        {
            return bc.GetUserInfos();
        }
    }
}

5 服务托起层 用iis把服务托起

<%@ ServiceHost language="C#" Debug="true" Service="Neower.UnicomVideo.BusinessFacade.UserInfoBF"%>

配置文件

   <?xml version="1.0"?> <configuration> <configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=null" requirePermission="true"/> <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/> <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> </sectionGroup> </sectionGroup> </sectionGroup> </configSections> <dataConfiguration defaultDatabase="UnicomVideoConnectionString"/> <appSettings> <add key="BaseUri" value="http://localhost/Service"/> </appSettings> <connectionStrings> <add name="UnicomVideoConnectionString" connectionString="Data Source=.;Database=TestDB;User Id=sa;Password=123;Pooling=true" providerName="System.Data.SqlClient"/> </connectionStrings> <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <alias alias="UserInfoBF" type="Neower.UnicomVideo.BusinessFacade.UserInfoBF, BusinessFacade"/> <alias alias="UserInfoBC" type="Neower.UnicomVideo.BusinessComponent.UserInfoBC, BusinessComponent"/> <alias alias="UserInfoDA" type="Neower.UnicomVideo.DataAccess.UserInfoDA, DataAccess"/> <container name="DataType"> <register type="UserInfoDA" mapTo="UserInfoDA"> </register> <register type="UserInfoBC" mapTo="UserInfoBC"> <constructor> <param name="userinfoDA" type="UserInfoDA"> <dependency name="userinfoDA" type="UserInfoDA"/> </param> </constructor> </register> </container> </unity> <system.web> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --> <compilation debug="true"> <assemblies> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> </compilation> <!-- The <authentication> section enables configuration of the security authentication mode used by ASP.NET to identify an incoming user. --> <authentication mode="Windows"/> <!-- The <customErrors> section enables configuration of what to do if/when an unhandled error occurs during the execution of a request. Specifically, it enables developers to configure html error pages to be displayed in place of a error stack trace. <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors> --> <pages> <controls> <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </controls> </pages> <httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/> </httpHandlers> <httpModules> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </httpModules> </system.web> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <providerOption name="CompilerVersion" value="v3.5"/> <providerOption name="WarnAsError" value="false"/> </compiler> </compilers> </system.codedom> <!-- The system.webServer section is required for running ASP.NET AJAX under Internet Information Services 7.0. It is not necessary for previous version of IIS. --> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <remove name="ScriptModule"/> <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </modules> <handlers> <remove name="WebServiceHandlerFactory-Integrated"/> <remove name="ScriptHandlerFactory"/> <remove name="ScriptHandlerFactoryAppServices"/> <remove name="ScriptResource"/> <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </handlers> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> <system.serviceModel> <services> <service behaviorConfiguration="serviceBehavior" name="Neower.UnicomVideo.BusinessFacade.UserInfoBF"> <endpoint behaviorConfiguration="endpointBehavior" bindingConfiguration="wsHttpBinding" binding="wsHttpBinding" contract="Neower.UnicomVideo.Common.IUserInfo"/> </service> </services> <bindings> <wsHttpBinding> <binding name="wsHttpBinding" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"> <readerQuotas maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="100" maxNameTableCharCount="2147483647" maxStringContentLength="2147483647"/> </binding> </wsHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="endpointBehavior"> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="serviceBehavior"> <serviceMetadata httpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>

主要是实现对象的创建 做到真正的IOC

6 代理层

  public class UserInfoProxy : ProxyBase<IUserInfo>, IUserInfo
    {
        public UserInfo[] GetUserInfos()
        {
            IUserInfo proxy = GetInstance();
            try
            {
                return proxy.GetUserInfos();
            }
            catch (CommunicationException)
            {
                (proxy as ICommunicationObject).Abort();
                throw;
            }
            catch (TimeoutException)
            {
                (proxy as ICommunicationObject).Abort();
                throw;
            }
            finally
            {
                (proxy as ICommunicationObject).Close();
            }
        }
        private IUserInfo GetInstance()
        {
            return this.GetObject("UserInfo");
        }
    }
}

基类

 public class ProxyBase<T>
        {
            public T GetObject(string endpoint)
            {
                return ProxyHelper.GetObject<T>(endpoint);
            }
         
        }
  

自己增加的工具类:   public static class ProxyHelper { public static void SetEndPointAddress<TChannel>(this ClientBase<TChannel> channel) where TChannel : class { string oldurl = channel.Endpoint.Address.Uri.AbsolutePath; oldurl = oldurl.Substring(oldurl.LastIndexOf("/")); string baseUri = ConfigurationManager.AppSettings["ClientBaseAdress"].Trim(); if (baseUri.EndsWith("/")) baseUri = baseUri.Substring(0, baseUri.Length - 1); if (!string.IsNullOrEmpty(baseUri)) { string newuri = string.Concat(baseUri, oldurl); EndpointAddress newAddress = new EndpointAddress(newuri); channel.Endpoint.Address = newAddress; } } #region ChannelFactory // Fields private static readonly Hashtable endpointKeyedChannelFactories = new Hashtable(); // Methods public static T GetObject<T>(string endpointName) { if (string.IsNullOrEmpty(endpointName)) { throw new ArgumentNullException("endpointName"); } ChannelFactory<T> factory = null; if (!endpointKeyedChannelFactories.ContainsKey(endpointName)) { factory = new ChannelFactory<T>(endpointName); lock (endpointKeyedChannelFactories.SyncRoot) { if (!endpointKeyedChannelFactories.ContainsKey(endpointName)) { endpointKeyedChannelFactories.Add(endpointName, factory); } } } if (factory == null) { factory = endpointKeyedChannelFactories[endpointName] as ChannelFactory<T>; } T instance = factory.CreateChannel(); if (typeof(T).GetInterfaces().Length == 0) { instance = Microsoft.Practices.EnterpriseLibrary.PolicyInjection.PolicyInjection.Wrap<T>(instance); } return instance; } public static Exception HandleWCFCommonException(ICommunicationObject proxy, Exception ex) { if ((ex is CommunicationException) || (ex is TimeoutException)) { proxy.Abort(); } return ex; } public static void Invoke<T>(string endpointName, Action<T> action) { T local = GetObject<T>(endpointName); IDisposable disposable = local as IDisposable; try { action(local); } catch (CommunicationException) { (local as ICommunicationObject).Abort(); throw; } catch (TimeoutException) { (local as ICommunicationObject).Abort(); throw; } finally { if (disposable != null) { disposable.Dispose(); } } } public static TResult Invoke<T, TResult>(string endpointName, Func<T, TResult> func) { TResult local2; T local = GetObject<T>(endpointName); IDisposable disposable = local as IDisposable; try { local2 = func.Invoke(local); } catch (CommunicationException) { (local as ICommunicationObject).Abort(); throw; } catch (TimeoutException) { (local as ICommunicationObject).Abort(); throw; } finally { if (disposable != null) { disposable.Dispose(); } } return local2; } #endregion }  

7 最后就是应用层了

   protected void Page_Load(object sender, EventArgs e)
        {
            UserInfoProxy proxy=new UserInfoProxy();
            UserInfo[] list = proxy.GetUserInfos();
            gv.DataSource = list;
            gv.DataBind();
        }

小弟把这个设计放到这里,希望高手指点一二。

 源代码http://download.csdn.net/source/3164585

你可能感兴趣的:(应用wCF 企业库搭建的一个Demo)