I have an ASP.NET Core 7 project that I use to connect to Dynamics 365 / Dataverse.
I do not use any services or interfaces as of now. In each controller I am creating a new instance of a ServiceClient
using Microsoft.PowerPlatform.Dataverse.Client
.
For example:
public class ContactsController : Controller
{
private readonly IConfiguration _configuration;
public ContactsController(IConfiguration configuration)
{
_configuration = configuration;
}
[Authorize]
public IActionResult Index()
{
string? connectionString = _configuration.GetConnectionString("Dataverse");
using (ServiceClient svc = new ServiceClient(connectionString))
{
if (svc.IsReady)
{
//Get data from Dataverse using svc
return View();
}
return View();
}
}
}
However, I know this approach is not good. I am not re-using the ServiceClient
and creating new ones for every call in each controller. I know that I should register the ServiceClient
and IOrganizationService
in Program.cs
like this for example:
builder.Services.AddScoped<IOrganizationService, ServiceClient>();
But I don't know how to write the interface and service class for this and how to add the connection string.
You could try using below code that the will create the
ServiceClient
and abstracts away the direct usage ofServiceClient
in your controllers.IOrganizationServiceWrapper.cs:
OrganizationServiceWrapper.cs:
Program.cs:
ContactsController.cs: