Dependency Injection within a Middleware .net Core 7

474 Views Asked by At

I am a newbie to .Net core and dependency Injection and trying to understand. I am working on a simple project for my understanding and having issues. In this project I am trying to access IHttpClientFactory to search for a city using a HTTP Get API.

The project is using .Net Core 7

I have a class called City.cs

public class City {
 public int Id {}
 public string CityName {}
}

Interface ICitySearch

public Interface ICitySearch {
 Task<List<City>> Search(string citytosearch);
}

CitySearchService.cs class to perform search using IHttpClientFactory

public class CitySearchService : ICitySearch
{
    private readonly IHttpClientFactory _clientFactory;
        

    public CitySearchService(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
       
    }

    public async Task<City> Search(string citytosearch)
    {
        var client = _clientFactory.CreateClient();

            var authString = Convert.ToBase64String(Encoding.UTF8.GetBytes("user:pass"));

            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authString);
            var response = await client.PostAsync("http://127.0.0.1:4080/api/worldcities/_search", new StringContent(value));
                    

            if (response.IsSuccessStatusCode)
            {
                using (var responseStream = await response.Content.ReadAsStreamAsync())
                {
                    var data = await System.Text.Json.JsonSerializer.DeserializeAsync
                        <City>(responseStream);
                }
            }
            else
            {
                // Do something else
            }
    }
}

In my Startup.cs

public void ConfigureServices(IServiceCollection services)
{

    services.AddHttpClient<ICitySearch, CitySearchService>();   
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IMemoryCache cache)
{

...

app.MapWhen(context => context.Request.Path.StartsWithSegments("/search.ashx"), Search.ProcessRequestAsync);

...

}

Search.cs class

public class Search 
{
        private readonly ICitySearch _city;

        public static void ProcessRequestAsync(IApplicationBuilder app)
        {

            app.Run(async context =>
            {
                   
                // How to do this. Can't figure this part.
                **_city.Search(context.Request.Query["city"]);**

            });
        }

}
                

How to access _city variable in Search.cs class under app.Run and perform the search?

Please help.

Thanks in advance.

1

There are 1 best solutions below

0
Eugene On

You can find RequestServices as a property of HttpContext. It's a dependency injection container which stores your service

            app.Run(async httpContext =>
            {  
                var citySearch = httpContext.RequestServices.GetRequiredService<ICitySearch>();
                citySearch.Search(httpContext.Request.Query["city"]);

            });