ServiceContainer

来源:互联网 发布:seo研究中心官网 编辑:程序博客网 时间:2024/05/27 01:46

把一项公共服务功能定义为一个Service(类);这样可以一次加入(AddService(type ,object)),多次使用(GetService(type))。另外在MSDN中还有其他成员操作ServiceContainer。


例子:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.ComponentModel.Design;

namespace ServiceContainer1
{
    public partial class ServiceContainerTest : DevExpress.XtraEditors.XtraForm
    {
        private ServiceContainer seContainer=new ServiceContainer();
        public ServiceContainerTest()
        {
            InitializeComponent();
        }

        private ServiceState state;
        public ServiceState State
        {
            get { return state; }
            set
            {
                state = value;
                switch (state)
                {
                    case ServiceState.ServiceObtained:
                        this.textBox1.BackColor = Color.Green;
                        break;
                    case ServiceState.ServiceRemoved:
                        this.textBox1.BackColor = Color.Red;
                        break;
                }
            }
        }
        private void btnRemoveService_Click(object sender, EventArgs e)
        {
            RemoveService();
        }

        private void btnAddService_Click(object sender, EventArgs e)
        {
            AddService();
        }

        private void AddService()
        {
            if (seContainer.GetService(typeof(TextService1)) != null)
            {
                var txService = seContainer.GetService(typeof(TextService1));
                this.textBox2.Text = (txService as TextService1).Title + "******" + (txService as TextService1).Content;
               
            }
            else
            {
                seContainer.AddService(typeof(TextService1), new TextService1 { Title = this.textBox1.Text, Content = "Commit" });
                this.textBox1.Text = this.textBox1.Text + "******Commit1";
            }
            State = ServiceState.ServiceObtained;
        }

        private void RemoveService()
        {
            if (seContainer.GetService(typeof(TextService1)) != null)
            {
                seContainer.RemoveService(typeof(TextService1));
                this.textBox1.Text = "RemoveSuccess";

            }
           
            State = ServiceState.ServiceRemoved;
        }
        public enum ServiceState
        {
            ServiceObtained=1,
            ServiceRemoved=2
        }
    }

    public class TextService1
    {
        public string Title { set; get; }
        public string Content { get; set; }
    }
}

原创粉丝点击