Nguon: Microsoft Learn · .NET 8.0

Chia sẻ controllers, views, Razor Pages và nhiều hơn với Application Parts trong ASP.NET Core

Nguồn: Share controllers, views, Razor Pages and more with Application Parts

Bởi Rick Anderson

Một Application Part (phần ứng dụng) là một lớp trừu tượng trên các tài nguyên của ứng dụng. Application Parts cho phép ASP.NET Core khám phá các controllers, view components (thành phần hiển thị), tag helpers, Razor Pages, nguồn biên dịch razor, và nhiều hơn nữa. AssemblyPart là một Application part. AssemblyPart đóng gói một tham chiếu assembly và hiển thị các kiểu và tham chiếu biên dịch.

Feature providers (nhà cung cấp tính năng) hoạt động cùng với application parts để điền vào các tính năng của ứng dụng ASP.NET Core. Trường hợp sử dụng chính cho application parts là cấu hình ứng dụng để khám phá (hoặc tránh tải) các tính năng ASP.NET Core từ một assembly. Ví dụ, bạn có thể muốn chia sẻ chức năng chung giữa nhiều ứng dụng. Sử dụng Application Parts, bạn có thể chia sẻ một assembly (DLL) chứa controllers, views, Razor Pages, nguồn biên dịch razor, Tag Helpers, và nhiều hơn với nhiều ứng dụng. Chia sẻ một assembly được ưu tiên hơn là nhân đôi code trong nhiều dự án.

Các ứng dụng ASP.NET Core tải các tính năng từ ApplicationPart. Lớp AssemblyPart đại diện cho một application part được hỗ trợ bởi một assembly.

Tải các tính năng ASP.NET Core

Sử dụng các lớp Microsoft.AspNetCore.Mvc.ApplicationPartsAssemblyPart để khám phá và tải các tính năng ASP.NET Core (controllers, view components, v.v.). ApplicationPartManager theo dõi các application parts và feature providers hiện có. ApplicationPartManager được cấu hình trong Startup.ConfigureServices:

csharp
// Yêu cầu using System.Reflection;
public void ConfigureServices(IServiceCollection services)
{
    var assembly = typeof(MySharedController).Assembly;
    services.AddControllersWithViews()
        .AddApplicationPart(assembly)
        .AddRazorRuntimeCompilation();

    services.Configure<MvcRazorRuntimeCompilationOptions>(options => 
    { options.FileProviders.Add(new EmbeddedFileProvider(assembly)); });
}

Đoạn code sau cung cấp một cách tiếp cận thay thế để cấu hình ApplicationPartManager sử dụng AssemblyPart:

csharp
// Yêu cầu using System.Reflection;
// Yêu cầu using Microsoft.AspNetCore.Mvc.ApplicationParts;
public void ConfigureServices(IServiceCollection services)
{
    var assembly = typeof(MySharedController).Assembly;
    // Tạo một AssemblyPart, nhưng không tạo các phần liên quan cho các mục như views.
    var part = new AssemblyPart(assembly);
    services.AddControllersWithViews()
        .ConfigureApplicationPartManager(apm => apm.ApplicationParts.Add(part));
}

Hai mẫu code trên đều tải SharedController từ một assembly. SharedController không nằm trong dự án của ứng dụng.

Bao gồm views

Sử dụng Razor class library để bao gồm views trong assembly.

Ngăn tải tài nguyên

Application parts có thể được sử dụng để tránh tải tài nguyên trong một assembly hoặc vị trí cụ thể. Thêm hoặc xóa các thành viên của bộ sưu tập Microsoft.AspNetCore.Mvc.ApplicationParts để ẩn hoặc làm tài nguyên có thể dùng được. Thứ tự của các mục trong bộ sưu tập ApplicationParts không quan trọng. Cấu hình ApplicationPartManager trước khi sử dụng nó để cấu hình services trong container. Ví dụ, cấu hình ApplicationPartManager trước khi gọi AddControllersAsServices. Gọi Remove trên bộ sưu tập ApplicationParts để xóa một tài nguyên.

ApplicationPartManager bao gồm các parts cho:

Feature providers (Nhà cung cấp tính năng)

Application feature providers kiểm tra application parts và cung cấp các tính năng cho những parts đó. Có các feature providers tích hợp sẵn cho các tính năng ASP.NET Core sau:

Feature providers kế thừa từ IApplicationFeatureProvider&lt;TFeature&gt;, trong đó T là kiểu của tính năng. Feature providers có thể được triển khai cho bất kỳ kiểu tính năng nào được liệt kê ở trên. Thứ tự của các feature providers trong ApplicationPartManager.FeatureProviders có thể ảnh hưởng đến hành vi lúc runtime (thời gian chạy). Các providers được thêm vào sau có thể phản ứng với các hành động được thực hiện bởi các providers được thêm vào trước.

Hiển thị các tính năng có sẵn

Các tính năng có sẵn cho một ứng dụng có thể được liệt kê bằng cách yêu cầu một ApplicationPartManager thông qua dependency injection (tiêm phụ thuộc):

csharp
using AppPartsSample.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Controllers;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Razor.Compilation;
using Microsoft.AspNetCore.Mvc.Razor.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewComponents;

namespace AppPartsSample.Controllers
{
    public class FeaturesController : Controller
    {
        private readonly ApplicationPartManager _partManager;

        public FeaturesController(ApplicationPartManager partManager)
        {
            _partManager = partManager;
        }

        public IActionResult Index()
        {
            var viewModel = new FeaturesViewModel();

            var controllerFeature = new ControllerFeature();
            _partManager.PopulateFeature(controllerFeature);
            viewModel.Controllers = controllerFeature.Controllers.ToList();

            var tagHelperFeature = new TagHelperFeature();
            _partManager.PopulateFeature(tagHelperFeature);
            viewModel.TagHelpers = tagHelperFeature.TagHelpers.ToList();

            var viewComponentFeature = new ViewComponentFeature();
            _partManager.PopulateFeature(viewComponentFeature);
            viewModel.ViewComponents = viewComponentFeature.ViewComponents.ToList();

            return View(viewModel);
        }
    }
}

Mẫu tải xuống sử dụng code trên để hiển thị các tính năng ứng dụng:

text
Controllers:
    - FeaturesController
    - HomeController
    - HelloController
    - GenericController`1
    - GenericController`1
Tag Helpers:
    - PrerenderTagHelper
    - AnchorTagHelper
    - CacheTagHelper
    - DistributedCacheTagHelper
    - EnvironmentTagHelper
    - Additional Tag Helpers omitted for brevity.
View Components:
    - SampleViewComponent

Khám phá trong application parts

Lỗi HTTP 404 không hiếm gặp khi phát triển với application parts. Những lỗi này thường được gây ra bởi việc thiếu một yêu cầu thiết yếu cho cách các application parts được khám phá. Nếu ứng dụng của bạn trả về lỗi HTTP 404, hãy xác minh các yêu cầu sau đã được đáp ứng: