使用 ASP.NET Core 中的第三方容器激活中间件Middleware activation with a third-party container in ASP.NET Core

本文内容

本文演示如何使用 IMiddlewareFactoryIMiddleware 作为使用第三方容器激活中间件的可扩展点。有关 IMiddlewareFactoryIMiddleware 的入门信息,请参阅 ASP.NET Core 中基于工厂的中间件激活

查看或下载示例代码如何下载

示例应用演示了使用 IMiddlewareFactorySimpleInjectorMiddlewareFactory 实现激活的中间件。此示例使用 Simple Injector 依赖项注入 (DI) 容器。

此示例的中间件实现记录了查询字符串参数 (key) 提供的值。中间件使用插入的数据库上下文(有作用域的服务)将查询字符串值记录在内存中数据库。

备注

此示例应用仅出于演示目的使用 Simple Injector不认可使用 Simple Injector。Simple Injector 文档中描述的中间件激活方法和 Simple Injector 维护人员推荐的 GitHub 问题。有关详细信息,请参阅 Simple Injector 文档Simple Injector GitHub 存储库

IMiddlewareFactoryIMiddlewareFactory

IMiddlewareFactory 提供中间件的创建方法。

在示例应用中,实现了中间件工厂以创建 SimpleInjectorActivatedMiddleware 实例。中间件工厂使用 Simple Injector 容器来解析中间件:

  1. public class SimpleInjectorMiddlewareFactory : IMiddlewareFactory
  2. {
  3. private readonly Container _container;
  4. public SimpleInjectorMiddlewareFactory(Container container)
  5. {
  6. _container = container;
  7. }
  8. public IMiddleware Create(Type middlewareType)
  9. {
  10. return _container.GetInstance(middlewareType) as IMiddleware;
  11. }
  12. public void Release(IMiddleware middleware)
  13. {
  14. // The container is responsible for releasing resources.
  15. }
  16. }

IMiddlewareIMiddleware

IMiddleware 定义应用的请求管道的中间件。

IMiddlewareFactory 实现 (Middleware/SimpleInjectorActivatedMiddleware.cs) 激活的中间件 :

  1. public class SimpleInjectorActivatedMiddleware : IMiddleware
  2. {
  3. private readonly AppDbContext _db;
  4. public SimpleInjectorActivatedMiddleware(AppDbContext db)
  5. {
  6. _db = db;
  7. }
  8. public async Task InvokeAsync(HttpContext context, RequestDelegate next)
  9. {
  10. var keyValue = context.Request.Query["key"];
  11. if (!string.IsNullOrWhiteSpace(keyValue))
  12. {
  13. _db.Add(new Request()
  14. {
  15. DT = DateTime.UtcNow,
  16. MiddlewareActivation = "SimpleInjectorActivatedMiddleware",
  17. Value = keyValue
  18. });
  19. await _db.SaveChangesAsync();
  20. }
  21. await next(context);
  22. }
  23. }

为中间件创建扩展 (Middleware/MiddlewareExtensions.cs) :

  1. public static class MiddlewareExtensions
  2. {
  3. public static IApplicationBuilder UseSimpleInjectorActivatedMiddleware(
  4. this IApplicationBuilder builder)
  5. {
  6. return builder.UseMiddleware<SimpleInjectorActivatedMiddleware>();
  7. }
  8. }

Startup.ConfigureServices 必须执行多项任务:

  • 设置 Simple Injector 容器。
  • 注册工厂和中间件。
  • 使 Simple Injector 容器提供应用的数据库上下文。
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddRazorPages();
  4. // Replace the default middleware factory with the
  5. // SimpleInjectorMiddlewareFactory.
  6. services.AddTransient<IMiddlewareFactory>(_ =>
  7. {
  8. return new SimpleInjectorMiddlewareFactory(_container);
  9. });
  10. // Wrap ASP.NET Core requests in a Simple Injector execution
  11. // context.
  12. services.UseSimpleInjectorAspNetRequestScoping(_container);
  13. // Provide the database context from the Simple
  14. // Injector container whenever it's requested from
  15. // the default service container.
  16. services.AddScoped<AppDbContext>(provider =>
  17. _container.GetInstance<AppDbContext>());
  18. _container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
  19. _container.Register<AppDbContext>(() =>
  20. {
  21. var optionsBuilder = new DbContextOptionsBuilder<DbContext>();
  22. optionsBuilder.UseInMemoryDatabase("InMemoryDb");
  23. return new AppDbContext(optionsBuilder.Options);
  24. }, Lifestyle.Scoped);
  25. _container.Register<SimpleInjectorActivatedMiddleware>();
  26. _container.Verify();
  27. }

中间件在 Startup.Configure 的请求处理管道中注册:

  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseDeveloperExceptionPage();
  6. }
  7. else
  8. {
  9. app.UseExceptionHandler("/Error");
  10. }
  11. app.UseSimpleInjectorActivatedMiddleware();
  12. app.UseStaticFiles();
  13. app.UseRouting();
  14. app.UseEndpoints(endpoints =>
  15. {
  16. endpoints.MapRazorPages();
  17. });
  18. }

本文演示如何使用 IMiddlewareFactoryIMiddleware 作为使用第三方容器激活中间件的可扩展点。有关 IMiddlewareFactoryIMiddleware 的入门信息,请参阅 ASP.NET Core 中基于工厂的中间件激活

查看或下载示例代码如何下载

示例应用演示了使用 IMiddlewareFactorySimpleInjectorMiddlewareFactory 实现激活的中间件。此示例使用 Simple Injector 依赖项注入 (DI) 容器。

此示例的中间件实现记录了查询字符串参数 (key) 提供的值。中间件使用插入的数据库上下文(有作用域的服务)将查询字符串值记录在内存中数据库。

备注

此示例应用仅出于演示目的使用 Simple Injector不认可使用 Simple Injector。Simple Injector 文档中描述的中间件激活方法和 Simple Injector 维护人员推荐的 GitHub 问题。有关详细信息,请参阅 Simple Injector 文档Simple Injector GitHub 存储库

IMiddlewareFactoryIMiddlewareFactory

IMiddlewareFactory 提供中间件的创建方法。

在示例应用中,实现了中间件工厂以创建 SimpleInjectorActivatedMiddleware 实例。中间件工厂使用 Simple Injector 容器来解析中间件:

  1. public class SimpleInjectorMiddlewareFactory : IMiddlewareFactory
  2. {
  3. private readonly Container _container;
  4. public SimpleInjectorMiddlewareFactory(Container container)
  5. {
  6. _container = container;
  7. }
  8. public IMiddleware Create(Type middlewareType)
  9. {
  10. return _container.GetInstance(middlewareType) as IMiddleware;
  11. }
  12. public void Release(IMiddleware middleware)
  13. {
  14. // The container is responsible for releasing resources.
  15. }
  16. }

IMiddlewareIMiddleware

IMiddleware 定义应用的请求管道的中间件。

IMiddlewareFactory 实现 (Middleware/SimpleInjectorActivatedMiddleware.cs) 激活的中间件 :

  1. public class SimpleInjectorActivatedMiddleware : IMiddleware
  2. {
  3. private readonly AppDbContext _db;
  4. public SimpleInjectorActivatedMiddleware(AppDbContext db)
  5. {
  6. _db = db;
  7. }
  8. public async Task InvokeAsync(HttpContext context, RequestDelegate next)
  9. {
  10. var keyValue = context.Request.Query["key"];
  11. if (!string.IsNullOrWhiteSpace(keyValue))
  12. {
  13. _db.Add(new Request()
  14. {
  15. DT = DateTime.UtcNow,
  16. MiddlewareActivation = "SimpleInjectorActivatedMiddleware",
  17. Value = keyValue
  18. });
  19. await _db.SaveChangesAsync();
  20. }
  21. await next(context);
  22. }
  23. }

为中间件创建扩展 (Middleware/MiddlewareExtensions.cs) :

  1. public static class MiddlewareExtensions
  2. {
  3. public static IApplicationBuilder UseSimpleInjectorActivatedMiddleware(
  4. this IApplicationBuilder builder)
  5. {
  6. return builder.UseMiddleware<SimpleInjectorActivatedMiddleware>();
  7. }
  8. }

Startup.ConfigureServices 必须执行多项任务:

  • 设置 Simple Injector 容器。
  • 注册工厂和中间件。
  • 使 Simple Injector 容器提供应用的数据库上下文。
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  4. // Replace the default middleware factory with the
  5. // SimpleInjectorMiddlewareFactory.
  6. services.AddTransient<IMiddlewareFactory>(_ =>
  7. {
  8. return new SimpleInjectorMiddlewareFactory(_container);
  9. });
  10. // Wrap ASP.NET Core requests in a Simple Injector execution
  11. // context.
  12. services.UseSimpleInjectorAspNetRequestScoping(_container);
  13. // Provide the database context from the Simple
  14. // Injector container whenever it's requested from
  15. // the default service container.
  16. services.AddScoped<AppDbContext>(provider =>
  17. _container.GetInstance<AppDbContext>());
  18. _container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
  19. _container.Register<AppDbContext>(() =>
  20. {
  21. var optionsBuilder = new DbContextOptionsBuilder<DbContext>();
  22. optionsBuilder.UseInMemoryDatabase("InMemoryDb");
  23. return new AppDbContext(optionsBuilder.Options);
  24. }, Lifestyle.Scoped);
  25. _container.Register<SimpleInjectorActivatedMiddleware>();
  26. _container.Verify();
  27. }

中间件在 Startup.Configure 的请求处理管道中注册:

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseDeveloperExceptionPage();
  6. }
  7. else
  8. {
  9. app.UseExceptionHandler("/Error");
  10. }
  11. app.UseSimpleInjectorActivatedMiddleware();
  12. app.UseStaticFiles();
  13. app.UseMvc();
  14. }

其他资源Additional resources