Instantiate client in a Sitecore context
Current version: 9.0
In a Sitecore context, the xConnect Client API is instantiated via a client configuration factory. A run-time model is assembled from any models listed in configuration. Search and collection connection strings are read from the App_Config\ConnectionStrings.config
file, which includes certificate thumbprints. The following example demonstrates how to get an instance of the xConnect Client API in a Sitecore context:
RequestResponse
using System.Linq;
using Sitecore.XConnect;
namespace Documentation
{
public class SearchResultsWithCount
{
// Async example
public async void Example()
{
using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
{
try
{
int count = await client.Contacts.Where(c => c.Identifiers.Any(t => t.IdentifierType == Sitecore.XConnect.ContactIdentifierType.Known)).Count();
}
catch (XdbExecutionException ex)
{
// Handle exception
}
}
}
// Sync example
public void ExampleSync()
{
using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
{
try
{
// There is no synchronous extension for Count - use SuspendContextLock instead
int count = Sitecore.XConnect.Client.XConnectSynchronousExtensions.SuspendContextLock(client.Contacts.Where(c => c.Identifiers.Any(t => t.IdentifierType == Sitecore.XConnect.ContactIdentifierType.Known)).Count);
}
catch (XdbExecutionException ex)
{
// Handle exception
}
}
}
}
}