简单注入器注入 PageModel ASP.NET Core Razor Pages

Simple Injector Inject into PageModel ASP.NET Core Razor Pages

简单注入器 (SI) 文档 here 展示了如何将 SI 与 ASP.NET 核心集成:

private void IntegrateSimpleInjector(IServiceCollection services) {
    container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddSingleton<IControllerActivator>(
        new SimpleInjectorControllerActivator(container));
    services.AddSingleton<IViewComponentActivator>(
        new SimpleInjectorViewComponentActivator(container));

    services.EnableSimpleInjectorCrossWiring(container);
    services.UseSimpleInjectorAspNetRequestScoping(container);
}

此示例代码展示了如何将 SI 与我们之前使用的控制器和 ViewComponents(MVC 模型)集成剃刀页面

但是,这并没有将 SI 集成到 Razor Pages 中,这是与 ASP.NET Core 2.0 一起发布的新功能。这基本上是一个 MVVM 模型(不完全是)。

所以 Razor 页面每个视图都有一个 PageModel,就像控制器一样。我想使用 SI.

注入这个 class 的构造函数

我想出了一种使用简单注入器注入 PageModel 的构造函数的方法:

public class SimpleInjectorPageModelActivatorProvider : IPageModelActivatorProvider
{
    private Container Container { get; }
    public SimpleInjectorPageModelActivatorProvider(Container c) => Container = c;
    public Func<PageContext, object> CreateActivator(CompiledPageActionDescriptor d) =>
        _ => Container.GetInstance(d.ModelTypeInfo.AsType());
    public Action<PageContext, object> CreateReleaser(CompiledPageActionDescriptor d) =>
        null;
}

然后,只需添加这个新的单例注册:

private void IntegrateSimpleInjector(IServiceCollection services)
{
    container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddSingleton<IControllerActivator>(
        new SimpleInjectorControllerActivator(container));
    services.AddSingleton<IViewComponentActivator>(
        new SimpleInjectorViewComponentActivator(container));

    // Enables Injection into PageModel
    services.AddSingleton<IPageModelActivatorProvider>(
            new SimpleInjectorPageModelActivatorProvider(container));

    services.EnableSimpleInjectorCrossWiring(container);
    services.UseSimpleInjectorAspNetRequestScoping(container);
}

它的作用基本上是在创建 PageModel 时调用 Container.GetInstance(instanceType)

Simple Injector 提供了一种使用扩展方法 A​​ddPageModelActivation.

实现此目的的简单方法
services.AddSimpleInjector(container, options =>
{
    // AddAspNetCore() wraps web requests in a Simple Injector scope.
    options.AddAspNetCore()
        // Ensure activation of a specific framework type to be created by
        // Simple Injector instead of the built-in configuration system.
        .AddControllerActivation()
        .AddViewComponentActivation()
        .AddPageModelActivation()
        .AddTagHelperActivation();
});

查看整个示例https://simpleinjector.readthedocs.io/en/latest/aspnetintegration.html