Stefan William-Worrall
Stefan William-Worrall

Reputation: 713

Create IOrganizationServiceFactory in Console Application for Dynamics CRM 2013

I am trying to create an instance of IOrganizationServiceFactory as I want to create multiple threads to connect to the service endpoind. To create multiple thread safe Service Contexts you can use the factory. However I can not seem to create one.

Is this possible within a C# Console Application or is it limited for only plugins and workflows ?

I can create a OrganizationServiceProxy, however I do not know how to proceed from here.

This is the code that I currently have:

var serverName = (string)ConfigurationManager.AppSettings["OrganisationUrl"];
Uri organisationUri = new Uri(string.Format("{0}/XRMServices/2011/Organization.svc", serverName));
Uri homeRealmUri = null;
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;


var serviceProxy = new OrganizationServiceProxy(organisationUri, homeRealmUri, credentials, null);

Upvotes: 1

Views: 2986

Answers (1)

Henk van Boeijen
Henk van Boeijen

Reputation: 7918

You can design a class implementing interface IOrganizationServiceFactory. This class can be made responsible for creating and issueing IOrganizationService instances.

I made a basic example:

class OrganizationServiceFactory: IOrganizationServiceFactory, IDisposable
{
    private readonly ConcurrentBag<OrganizationServiceProxy> _issuedProxies =
        new ConcurrentBag<OrganizationServiceProxy>(); 

    public IOrganizationService CreateOrganizationService(Guid? userId)
    {
        var serverName = (string)ConfigurationManager.AppSettings["OrganisationUrl"];
        Uri organisationUri = new Uri(string.Format("{0}/XRMServices/2011/Organization.svc", serverName));
        var credentials = new ClientCredentials();
        credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;

        var serviceProxy = new OrganizationServiceProxy(organisationUri, null, credentials, null);
        _issuedProxies.Add(serviceProxy);
        return serviceProxy;
    }

    public void Dispose()
    {
        foreach (var serviceProxy in _issuedProxies)
        {
            serviceProxy.Dispose();
        }
    }
}

Clients of the factory can obtain IOrganizationService instances by calling CreateOrganizationService(Guid? userId), but cannot be responsible for disposing the proxies. The factory will do that for them.

B.t.w, you can make the creation of multiple proxy-instances a bit more efficient using the IServiceManagement<IOrganizationService> interface, but that's another topic.

You may find this article on MSDN useful: Optimize CRM 2011 Service Channel allocation for multi-threaded processes.

Upvotes: 2

Related Questions