Managing WCF service instances

24 בנובמבר 2007

אין תגובות

When you first time run your WCF service (http://localhost/myCoolService.svc) you get a nice tutorial, made by Microsoft, that explain you how you should use the service. This is not hard to notice that you should close every connection you made to a service. Like this:

MyServiceClient client = new MyServiceClient();

I am using a lot of services in my apps and I don’t want to kip in mind that all the time I am using a service instance I have to remember to close the connection. So I wrote a simple code that handles the closing for me.

public class ServicesFactory : IDisposable
    List<object> services;

    public ServicesFactory()
        services = new List<object>();

    public T CreateService<T>() where T : ICommunicationObject
        T service = Activator.CreateInstance<T>();
        return service;

    #region IDisposable Members

    public void Dispose()
        foreach (object obj in services)
            ICommunicationObject currService = (ICommunicationObject)obj;
            if (currService.State != CommunicationState.Closed)



Now every time I will create a service instance I will do it this way.

using (ServicesFactory factory = new ServicesFactory())
    WCFServiceEx.Client.Calculate.CalculateClient client = 

    // do service logic.

That will make shore that the connection of all the instances that I made in the scope will be closed as soon as the code in the scope will finished.

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *