c# Unity依賴注入WebService

1.IOC與DI簡介web

  IOC全稱是Inversion Of Control(控制反轉),不是一種技術,只是一種思想,一個重要的面相對象編程的法則,它能知道咱們如何設計出鬆耦合,更優良的程序。傳統應用程序都是由咱們在類內部主動建立依賴對象,從而致使類與類之編程

間高耦合,難於測試;有了IoC容器後,把建立和查找依賴對象的控制權交給了容器,由容器進行注入組合對象,因此對象與對象之間是鬆散耦合,這樣也方便測試,利於功能複用,更重要的是使得程序的整個體系結構變得很是靈活。其實IoC測試

對編程帶來的最大改變不是從代碼上,而是從思想上,發生了「主從換位」的變化。應用程序本來是老大,要獲取什麼資源都是主動出擊,可是在IoC/DI思想中,應用程序就變成被動的了,被動的等待IoC容器來建立並注入它所須要的資源ui

了。  this

  IoC很好的體現了面向對象設計法則之—— 法則:「別找咱們,咱們找你」;即由IoC容器幫對象找相應的依賴對象並注入,而不是由對象主動去找。spa

  DI全稱是Dependency Injection(依賴注入),是組件之間依賴關係有容器在運行期決定,即由容器動態的將某個依賴關係注入到組件之中,依賴注入的目的並不是軟件系統帶來更多的功能,設計

而是爲了提高組件重用的頻率,併爲系統搭建一個靈活可擴展的平臺。經過依賴注入機制,咱們只須要經過簡單的配置,而無需代碼指定目標須要的資源,完成自身的業務邏輯,而不須要關心具體的資源來自何處code

  DI的關鍵是:「誰依賴誰,爲何須要依賴,誰注入水,注入了什麼」orm

2.Unity IOC簡介對象

  Unity是一個IOC容器,用來實現依賴注入(DI)減小耦合,出自於微軟。

  組件地址:http://unity.codeplex.com/

3.使用Unity依賴注入編寫Web ServiceDemo

  a。使用NuGet程序包管理安裝引用Unity  

  b。在Global.asax中配置容器

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Microsoft.Practices.Unity;
using WebServiceDemo.Impl;
using WebServiceDemo.Interface;

namespace WebServiceDemo
{
    public class Global : System.Web.HttpApplication,IContainerAccessor
    {

        private static IUnityContainer _container;

        public static IUnityContainer Container {
            get { return _container; }
            set { _container = value; }

        }

        IUnityContainer IContainerAccessor.Container
        {
            get
            {
                return Container;
            }
        }

        protected void Application_Start(object sender, EventArgs e)
        {

            log4net.Config.XmlConfigurator.Configure();
            CreateContainer();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

        protected virtual void CreateContainer()
        {
            IUnityContainer container = new UnityContainer();

            container.RegisterType<IWebServiceDemo, WebServiceDemo>();          

            Container = container;
        }
    }
}

  

  c。建立服務接口基類

  

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebServiceDemo.Interface;

namespace WebServiceDemo.Services
{
    public abstract class BaseService<T> :System.Web.Services.WebService where T:class
    {
        public BaseService()
        {
            InjectDependencies();
        }

        protected virtual void InjectDependencies()
        {
            HttpContext context = HttpContext.Current;

            if (context == null)
                return;

            IContainerAccessor accessor = context.ApplicationInstance as IContainerAccessor;

            if (accessor == null)
                return;

            IUnityContainer container = accessor.Container;

            if (container==null)
            {
                throw new InvalidOperationException("Container on Global Application Class is Null. Cannot perform BuildUp.");
            }

            container.BuildUp(this as T);
            
        }
    }
}

  d。建立實現服務的接口和實現類

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebServiceDemo.Dto;

namespace WebServiceDemo.Interface
{
    public  interface IWebServiceDemo
    {
        RespResult<ResultOutput> AddResult(int a,int b);
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebServiceDemo.customize;
using WebServiceDemo.Dto;
using WebServiceDemo.Interface;

namespace WebServiceDemo.Impl
{
    public class WebServiceDemoImpl : IWebServiceDemo
    {

        private static readonly ILog log = LogManager.GetLogger(typeof(BeingSweptServiceImpl));

        public RespResult<ResultOutput> AddResult(int a,int b)
        {
            return a+b;

        }
    }
}

  

  e。建立配置Webservice

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using WebServiceDemo.customize;
using WebServiceDemo.Interface;
using Microsoft.Practices.Unity;
using WebServiceDemo.Dto;

namespace WebServiceDemo.Services
{
    /// <summary>
    /// Summary description for MainSweepService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class ServiceDemoService : BaseService<ServiceDemoService>
    {
        [Dependency]
        public IWebServiceDemo _webServiceDemo
        {
            get; set;
        }

        public ServiceDemoService () : base()
        {

        }

        [WebMethod(Description ="加法")]
        public RespResult<ResultOutput> AddResult(int a,int b)
        {
            return this._webServiceDemo.AddResult(a,b);
        }

    }

}
相關文章
相關標籤/搜索