-2

I am working on .NET Core.

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

The CreateHostBuilder method returns IHostBuilder interface and is calling the Build method of that. So is it possible to implement code inside that interface or is it any design pattern?

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
  • I am unclear as to what you are asking. Can you reformat the question so we get a clearer picture of the current problem and what you are **actually** trying to do? See the [ask] page for help clarifying this question. – Nkosi Dec 01 '19 at 10:33

2 Answers2

0

CreateHostBuilder method return type which implement interface IHostBuilder and Build method on that returned type is getting called.

Roshan
  • 873
  • 12
  • 33
  • but we can't implement interface. then how we can call method of that interface? – rushang panchal Dec 01 '19 at 05:48
  • 1
    @rushangpanchal: Consider a type you are familiar with, `System.String`. it implements `IComparable`. I can write code like `var s="abc"; var ic=(IComparable)s;`. At this point, the variable `ic` doesn't know it's referring to a string, only to an instance of some type that implements `IComparable`. Just like if it was set as the result of calling some function that returned `IComparable`. About the only thing I can do with `ic` is call `ic.CompareTo(something)`. It's still a string under the covers, but it's only `IComparable` from the `ic` point of view – Flydog57 Dec 01 '19 at 05:59
0

The class isn't sealed, but Build isn't virtual, so it is a bit of a challenge to extend it. But you can always wrap the object and implement the interface in the wrapper, passing through control or overriding or extending whatever behavior you want.

public class MyHostBuilder : IHostBuilder
{
    protected readonly IHostBuilder _inner;

    public MyHostBuilder(IHostBuilder inner)
    {
        _inner = inner;
    }

    public IHost Build()
    {
        DoSomethingCustom();
        return _inner.Build();          //Do something custom then pass through
    }

    public void ConfigureContainer<TContainerBuilder>(Action<HostBuilderContext,TContainerBuilder> action)
    {
        _inner.ConfigureContainer(action);  //Pass through without extending
    }
}        
John Wu
  • 50,556
  • 8
  • 44
  • 80