次の方法で共有


Creating a custom instance of a Service inside Indigo

 When you setup an Indigo service in the default way, it is not possible to use anything other than the default constructor for creating your object.  There are two ways you can setup a custom object to use as your service instance, the first is to use a well known object as the service when you add the endpoint.  This means that the instance effectively operates as if it is a singleton, but you control which object it uses as the singleton.  To achieve this behavior when you setup a ServiceHost<T> you pass in a T to the constructor.

The second mechanism you can use to setup your own object for the system is that you can hook into the IServiceDispatcher code and return your own instance from the GetInstance call.  You can return anything you like from the GetInstance call, but it must conform to the originaly specified contract and must be of the correct type, or the calls will not be made on it.

Some example code of how to hook up the GetObject call follows.  You are also informed when an object is Released in case you want to do some pooling.  If you hook up the GetObject and ReleaseObject calls you will need to control yourself when the Dispose is called on the objects and any other cleanup that is done on the service instance once it is released.

    [ServiceBehavior(InstanceMode = InstanceMode.PerCall)]
    [CLSCompliant(false)]
    public partial class ServiceCallTest : IInstanceProvider, ISiteInitializer,
IContractBehavior, IServiceTest
    {
        public void Bar(string n)
        {
            System.Console.WriteLine("Bar(" + n + ")");
            return;
        }

        #region IContractBehavior Members

        public void BindProxy(ContractDescription desc, System.ServiceModel.ProxyBehavior proxy)
        {
        }

        public void BindDispatch(ContractDescription desc, System.ServiceModel.DispatchBehavior dispatch)
        {
            dispatch.InstanceProvider = this;
            dispatch.SiteInitializers.Add(this);
        }

        #endregion

        public object GetInstance(ServiceSite site, Message incoming)
        {
            System.Console.WriteLine("GetObject.");
            return new ServiceCallTest();
        }

        public void ReleaseInstance(ServiceSite site, object instanct)
        {
            System.Console.WriteLine("ReleaseObject.");
        }

        public void Initialize(ServiceSite site, Message mess)
        {
            System.Console.WriteLine("Initialize.");
        }
    }