How to reduce recreation of ElasticClient (ASP.NET MVC C#)

Hello There,

Please accept my apologies in advance for bad English. I do not have much knowledge of programming concepts and I am new to elasticsearch.

Preparing a sample using Elasticsearch NEST in ASP.NET MVC C#.

I have prepared a class with an static function which return ElasticClient.

public class ElasticSeachConfiguration
    {
        public static ElasticClient ESContext()
        {                                        
            var settings = new ConnectionSettings(new Uri("http://localhost:9200"));
            var client = new ElasticClient(settings);
            return client;
        }
} 

Now the problem is that when ever I need to communicate with elasticsearch I am using ElasticSeachConfiguration.ESContext() and each time it is creating new ConnectionSetting and new elastic client.

For example ->

public void CreateEmployee(Employee emp)
        {
            ElasticSeachConfiguration.ESContext().Index(emp, i => i.Index("myindex").Type("employee").Id(emp.Id));
        }

public void UpdateEmployee(Employee emp)
        {
            ElasticSeachConfiguration.ESContext().Index(emp, i => i.Index("myindex").Type("employee").Id(emp.Id));
 ElasticSeachConfiguration.ESContext().Update<Employee, object>(new DocumentPath<Employee>(emp.Id), u => u
                       .Index("myindex").Type("employee")
                       .Doc(emp));
        }

I am not feeling good about it .. I am sure I am making a blunder related to programming concepts .. I need your guidance .. please share your suggestions .. what should I explore so that I can understand the concepts to write classes in correct pattern .. to stop unnecessary execution of the code .. I hope my request is clear ..sharing temp link for sample code I prepared

https://expirebox.com/download/4ff263e1c85aff1afc6fb8829cce664c.html

Thanks in advance.

Please reply

you can implement the Singleton pattern so that only a single instance of IElasticClient is instantiated

public sealed class ElasticSeachConfiguration
{
    private static readonly ElasticClient instance = 
        new ElasticClient(new ConnectionSettings(new Uri("http://localhost:9200")));

    public static IElasticClient ESContext => instance;

    static ElasticSeachConfiguration() { }
    private ElasticSeachConfiguration() { }
} 

As an alternative approach, ASP.NET MVC provides the ability to hook in an Inversion of Control (IoC) container to implement Dependency Injection, such that the container will instantiate an instance of a component for you, and manage its lifecycle/lifestyle according to how it is configured with the container

Here's an example with ASP.NET Core.

In Startup.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        // register the client as a singleton
        services.Add(ServiceDescriptor.Singleton<IElasticClient>(
            new ElasticClient(new ConnectionSettings(new Uri("http://localhost:9200")))));
    }
}

Now, in your controllers, you can have an instance of IElasticClient injected into an instance of a controller for you

public class SearchController : Controller
{
	private readonly IElasticClient _client;

	// container will inject client into controller
	public SearchController(IElasticClient client) => _client = client;

	[HttpGet]
	public IActionResult Index()
	{
		var response = _client.Search<Package>(s => s
			.MatchAll()
		);

		var model = new SearchViewModel
		{
			Hits = response.Hits,
			Total = response.Total
		};

		return View(model);
	}
}
2 Likes

Thank you so much for your reply .. I will follow you suggestion and will try to educate myself further,

Thanks again.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.