Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't anything passed to the .UseStartup<Startup>() method in default webapi .Net Core application?

Upon creating a .Net Core webapi application, the following code is created in Program.cs:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace dotnet_testing
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

Why isn't anything passed to the .UseStartup() method?

WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();

From what I'm understanding in the "WebHostBuilderExtensions.UseStartup Method" documentation, you are supposed to pass an IWebHostBuilder:

UseStartup<TStartup>(IWebHostBuilder)

I'm not seeing a dependency injection in the "using" statements, so it doesn't seem to be injected.

like image 966
Dedicated Managers Avatar asked Oct 11 '25 13:10

Dedicated Managers


1 Answers

if we take a closer look to the signature of the method

public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseStartup<TStartup>
  (this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder) where TStartup : class;

we will see that it is An Extension Method, hence it uses itself as parameter.

Edit: Info About Extension Methods

this keyword points itself. Lets say that we need to write Extension Method which dublicates string. then,

public static class StringExtensions {
    public static string DublicateString(this string myString) => $"{myString}{myString}";
}

then in order to use it

var str = "JohnDoe";
var result = str.DublicateString();

The compiler automatically translates str.DublicateString() into:

var str = "JohnDoe";
var result = StringExtensions.DublicateString(str);
like image 65
Derviş Kayımbaşıoğlu Avatar answered Oct 14 '25 09:10

Derviş Kayımbaşıoğlu