我们如何在.NET Core中使用Simple Injector Bootstrapper?

时间:2018-02-12 08:43:07

标签: asp.net-core

我们如何在.NET Core Web Api项目中使用Simple Injector Bootstrapper?实际上我们在这里尝试使用外部库进行简单的注入是代码:

public static class IdentityServerBootstrapper
{
    public static void Bootstrap(Container container, IEnumerable<Assembly> assemblies = null, bool verifyContainer = true)
    {
        container.Register<ISUPCoreApiClient>(() => new SUPCoreApiClient("https://localhost:44329/"));

        if (verifyContainer)
        {
            container.Verify();
        }
    }
}

这是web api项目中的bootstrapper类

 public class WebApiBootstrapper
{
    public static void Bootstrap(Container container)
    {

        IdentityServerBootstrapper.Bootstrap(container, null, false);

        container.Verify();
    }
}

这是启动类:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();



        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

        WebApiBootstrapper.Bootstrap(container);
    }

但它不起作用..

1 个答案:

答案 0 :(得分:0)

找到here

的原始解决方案

我用一些扩展实现了它,而IMO是一种更好的方法。

扩展

public static class ConfigureContainerExtensions
{
    public static void Bootstrap(this IServiceCollection services, Container container)
    {
        container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddSingleton<IControllerActivator>(
            new SimpleInjectorControllerActivator(container));

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

    public static void InitializeContainer(this IApplicationBuilder app, 
        Container container, IConfiguration configuration)
    {
        container.RegisterMvcControllers(app);
        WebApiBootstrapper.Bootstrap(container);
    }
}

在启动课程中使用它们:

private Container _container;

public void ConfigureServices(IServiceCollection services)
{
    services.Bootstrap(_container);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.InitializeContainer(_container, Configuration);
}