7 kinds dependency injection ASP.NET Core Application

19327-20200323085612647-219130351ASP.NET Core framework many core objects are provided by way of injection-dependent, such as the Startup object to initialize the application, middleware, objects, and ASP.NET Core MVC application View Controller object and other objects, so we can define them when injected in the form of service to the consumer already registered. Following is a brief scenario of several service injection. This article excerpt from "ASP.NET Core 3 framework Secret", 5% discount for the book as well as the last two days , are interested can scan two-dimensional code, or the right from here into the group purchase. .

First, injection type constructor Startup

Two core configuration HostBuilderContext context objects (represented configured IConfiguration objects representing the host environment IHostEnvironment objects) may be directly injected into the Startup constructor for consumption. Because ASP.NET Core application hosting environment represented by IWebHostEnvironment interfaces, interfaces IHostEnvironment IWebHostEnvironment interface is on, it is also possible by injecting IWebHostEnvironment obtained environment information related to the current bearer mode object.

We can through a simple example to validate injection for the constructor Startup. The following code fragment we call IWebHostBuilder interface Startup <TStartup> method registered custom type when Startup. When defining Startup type, we inject the three objects in its constructor, debug assertion provide not only proved the three object is not Null, also showed that the use of IHostEnvironment IWebHostEnvironment interfaces and connectors which were in fact one and the same instance.

class Program
{
    static void Main()
    {
        Host.CreateDefaultBuilder().ConfigureWebHostDefaults(builder => builder.UseStartup<Startup>())
        .Build()
        .Run();
    }
}

public class Startup
{
    public Startup ( IConfiguration configuration, IHostEnvironment hostingEnvironment, IWebHostEnvironment webHostEnvironment )
    {
        Debug.Assert(configuration != null);
        Debug.Assert(hostingEnvironment != null);
        Debug.Assert(webHostEnvironment != null);
        Debug.Assert(ReferenceEquals(hostingEnvironment, webHostEnvironment));
    }
    public void Configure(IApplicationBuilder app) { }
}

Second, the injection process Startup type Configure

Dependent services can also be injected directly into the Configure method for registration of middleware. If the constructor injection to injection can also have a choice of service, then for Configure method, the registration service by any means which can be injected, including by calling IHostBuilder, IWebHostBuilder and Startup their ConfigureServices method of registration services, including framework of self-registration of all services.

The following code fragment of code, and we call respectively IWebHostBuilder Startup ConfigureServices method of registration and service interfaces for IFoo IBar interfaces, two service Configure direct injection method of Startup. In addition, Configure method requires an object to provide a IApplicationBuilder registered middleware used as an argument, but did not make any restrictions on the location parameters appear.

class Program
{
    static void Main()
    {
        Host.CreateDefaultBuilder().ConfigureWebHostDefaults(builder => builder
            .UseStartup<Startup>()
            .ConfigureServices(svcs => svcs.AddSingleton<IFoo, Foo>()))
        .Build()
        .Run();
    }
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services) => services.AddSingleton<IBar, Bar>();
    public void Configure(IApplicationBuilder app, IFoo foo, IBar bar)
    {
        Debug.Assert(foo != null);
        Debug.Assert(bar != null);
    }
}

Three, injection type constructor in the middleware

The most important objects ASP.NET Core middleware request processing pipeline is used to actually handle the request. Because ASP.NET Core middleware in the creation of objects and they build the entire request processing pipeline utilization, all the services are already registered, so any registered services can be injected into the middleware type constructor. Code snippet shown below reflects the middleware type for injection constructor.

class Program
{
    static void Main()
    {
        Host.CreateDefaultBuilder().ConfigureWebHostDefaults(builder => builder
            .ConfigureServices(svcs => svcs
                .AddSingleton<FoobarMiddleware>()
                .AddSingleton<IFoo, Foo>()
                .AddSingleton<IBar, Bar>())
            .Configure(app => app.UseMiddleware<FoobarMiddleware>()))
        .Build()
        .Run();
    }
}

public class FoobarMiddleware : IMiddleware
{
    public FoobarMiddleware(IFoo foo, IBar bar)
    {
        Debug.Assert(foo != null);
        Debug.Assert(bar != null);
    }

    public Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        Debug.Assert(next != null);
        return Task.CompletedTask;
    }
}

Fourth, the intermediate injection type Invoke / InvokeAsync method

If the middleware type is defined based on the agreed way, the service can also be registered directly injected InvokeAsync Invoke method or methods for processing a real request. In addition, a method named InvokeAsync more in line with TAP (Task-based Asynchronous Pattern) programming mode, the reason to retain the Invoke method name, primarily for version compatibility purposes. Code snippet shown below shows a service for InvokeAsync implantation method.

class Program
{
    static void Main()
    {
        Host.CreateDefaultBuilder().ConfigureWebHostDefaults(builder => builder
            .ConfigureServices(svcs => svcs
                .AddSingleton<IFoo, Foo>()
                .AddSingleton<IBar, Bar>())
            .Configure(app => app.UseMiddleware<FoobarMiddleware>()))
        .Build()
        .Run();
    }
}

public class FoobarMiddleware
{
    private readonly RequestDelegate _next;

    public FoobarMiddleware(RequestDelegate next) => _next = next;
    public Task InvokeAsync(HttpContext context, IFoo foo, IBar bar)
    {
        Debug.Assert(context != null);
        Debug.Assert(foo != null);
        Debug.Assert(bar != null);
        return _next(context);
    }
}

Although the agreed definition of middleware types and the Startup type uses a similar service injection method, they all support constructor injection and injection methods, but there are some differences between them. Middleware type constructors, methods Configure the Startup type and middleware type InvokeAsync Invoke method or methods having a required parameter, which are type RequestDelegate, IApplicationBuilder the HttpContext and, for this position in the entire list parameter, the front neither do any restriction, which requires only that the current request context parameter must HttpContext method as the first parameter. According to the above convention, this is defined as follows FoobarMiddleware middleware type is not legal, but Starup type definition is valid. For this, I believe that this limit can be open, so that not only the definition of middleware type is more flexible, but also to ensure consistency injection method.

public class FoobarMiddleware
{
    public FoobarMiddleware(RequestDelegate next);
    public Task InvokeAsync(IFoo foo, IBar bar, HttpContext context);
}

public class Startup
{
    public void Configure(IFoo foo, IBar bar, IApplicationBuilder app);
}

For injection essential difference exists a middleware, and constructor injection based on the prescribed manner. Because middleware is registered as a Singleton object, so we should not be injected in its constructor Scoped services. Scoped middleware service can only type InvokeAsync injection process , as are dependent services for a range of services provided in the current request, it is possible to secure Scoped be released after the current service request processing ends.

V. injection type constructor Controller

In an ASP.NET Core MVC application, we can constructor injection manner inject services defined in the Controller. In the code fragment shown below, we will IFoobar service injected into the constructor HomeController.

class Program
{
    static void Main()
    {
        Host.CreateDefaultBuilder().ConfigureWebHostDefaults(builder => builder
            .ConfigureServices(svcs => svcs
                .AddSingleton<IFoobar, Foobar>()
                .AddSingleton<IBar, Bar>()
                .AddControllersWithViews())
            .Configure(app => app
                .UseRouting()
                .UseEndpoints(endpoints => endpoints.MapControllers())))
        .Build()
        .Run();
    }
}

public class HomeController : Controller
{
    public HomeController(IFoobar foobar) => Debug.Assert(foobar != null);

}

Sixth, in the injection method of Action Controller of

By means of ASP.NET Core MVC model based on parameter binding mechanism for binding, we can register a service bound to the target parameter Action methods, so as to realize the injection method for the dependence of Action. When using this type of injection method, we need to mark in the following manner on the injection parameters FromServicesAttribute characteristics, to determine the source parameter binding is a registered service.

class Program
{
    static void Main()
    {
        Host.CreateDefaultBuilder().ConfigureWebHostDefaults(builder => builder
            .ConfigureServices(svcs => svcs
                .AddSingleton<IFoobar, Foobar>()
                .AddControllersWithViews())
            .Configure(app => app
                .UseRouting()
                .UseEndpoints(endpoints => endpoints.MapControllers())))
        .Build()
        .Run();
    }
}

public class HomeController: Controller
{
    [HttpGet("/")]
    public void Index([FromServices]IFoobar foobar)
    {
        Debug.Assert(foobar != null);
    }
}

Seven injected in the view

In ASP.NET Core MVC application, we can also now registered to the service of View. Suppose we define the following simple MVC program, and defines a simple HomeController.

class Program
{
    static void Main()
    {
        Host.CreateDefaultBuilder().ConfigureWebHostDefaults(builder => builder
            .ConfigureServices(svcs => svcs
                .AddSingleton<IFoobar, Foobar>()
                .AddControllersWithViews())
            .Configure(app => app
                .UseRouting()
                .UseEndpoints(endpoints => endpoints.MapControllers())))
        .Build()
        .Run();
    }
}

public class HomeController: Controller
{
        [HttpGet("/")]
        public IActionResult Index() => View();
}

Before we define a routing path to the root ( "/") method of Action Index is HomeController, the method presented in the default View View method invocation, the injected IFoo service delivery to the View to ViewBag form. Code snippet shown below that this method corresponds to the definition of Action View (/Views/Home/Index.cshtml), we injected through @inject IFoobar service instruction and attribute name to Foobar, this means that the current View object Foobar property to add a reference injection service.

@inject IFoobar Foobar
@
{
    Debug.Assert(Foobar!= null);
}

Guess you like

Origin www.cnblogs.com/artech/p/di-in-asp-net-core-3.html