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

**URL:** <https://discuss.elastic.co/t/how-to-reduce-recreation-of-elasticclient-asp-net-mvc-c/115216>\
**Category:** Elasticsearch\
**Created:** [January 12, 2018, 5:52am UTC](https://discuss.elastic.co/t/how-to-reduce-recreation-of-elasticclient-asp-net-mvc-c/115216 "2018-01-12T05:52:44Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![nmathur](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/nmathur/32/21451_2.png) [@nmathur](https://discuss.elastic.co/u/nmathur)\
**Post date:** [January 12, 2018, 5:52am UTC](https://discuss.elastic.co/t/how-to-reduce-recreation-of-elasticclient-asp-net-mvc-c/115216/1 "2018-01-12T05:52:44Z")

</div>

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](http://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](https://expirebox.com/download/4ff263e1c85aff1afc6fb8829cce664c.html)

Thanks in advance.

---

<div class="post-metadata">

**Author:** ![nmathur](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/nmathur/32/21451_2.png) [@nmathur](https://discuss.elastic.co/u/nmathur)\
**Post date:** [January 13, 2018, 9:37am UTC](https://discuss.elastic.co/t/how-to-reduce-recreation-of-elasticclient-asp-net-mvc-c/115216/2 "2018-01-13T09:37:01Z")

</div>

Please reply

---

<div class="post-metadata">

**Author:** ![forloop](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/forloop/32/9021_2.png) [@forloop](https://discuss.elastic.co/u/forloop)\
**Post date:** [January 14, 2018, 11:17pm UTC](https://discuss.elastic.co/t/how-to-reduce-recreation-of-elasticclient-asp-net-mvc-c/115216/3 "2018-01-14T23:17:34Z")

</div>

you can implement [the Singleton pattern](https://en.wikipedia.org/wiki/Singleton_pattern) so that only a single instance of `IElasticClient` is instantiated

```auto
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](http://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](http://ASP.NET) Core.

In Startup.cs

```auto
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

```auto
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);
	}
}

```

---

<div class="post-metadata">

**Author:** ![nmathur](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/nmathur/32/21451_2.png) [@nmathur](https://discuss.elastic.co/u/nmathur)\
**Post date:** [January 15, 2018, 5:14am UTC](https://discuss.elastic.co/t/how-to-reduce-recreation-of-elasticclient-asp-net-mvc-c/115216/4 "2018-01-15T05:14:01Z")

</div>

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

Thanks again.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [February 12, 2018, 5:14am UTC](https://discuss.elastic.co/t/how-to-reduce-recreation-of-elasticclient-asp-net-mvc-c/115216/5 "2018-02-12T05:14:33Z")

</div>

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