简体   繁体   中英

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);

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.

Btw, 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM