简单的注入器注入PageModel ASP.NET核心Razor页面

问题描述 投票:4回答:1

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

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与我们在Razor Pages之前使用的控制器和ViewComponents(MVC模型)集成。

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

所以Razor页面每个视图都有一个PageModel,它就像控制器一样。我想使用SI注入这个类的构造函数。

c# asp.net-core .net-core simple-injector razor-pages
1个回答
4
投票

我想到了一种使用Simple Injector注入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)


0
投票

Simple Injector提供了一种使用扩展方法AddPageModelActivation实现此目的的简单方法。

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

© www.soinside.com 2019 - 2024. All rights reserved.