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

时间:2018-04-27 15:04:49

标签: c# asp.net-core .net-core simple-injector razor-pages

简单注入器( 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 MVC 模型)集成>

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

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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