Azure 如何将服务结构服务上下文注入asp.net核心中间件?
我有一个实现自定义中间件的服务结构asp.net核心无状态服务。在该中间件中,我需要访问我的服务实例。我将如何使用asp.NETCore的内置DI/IoC系统注入此功能Azure 如何将服务结构服务上下文注入asp.net核心中间件?,azure,asp.net-core,azure-service-fabric,Azure,Asp.net Core,Azure Service Fabric,我有一个实现自定义中间件的服务结构asp.net核心无状态服务。在该中间件中,我需要访问我的服务实例。我将如何使用asp.NETCore的内置DI/IoC系统注入此功能 public class MyMiddleware { private readonly RequestDelegate _next; public MyMiddleware(RequestDelegate next) { _next = next; } public
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext httpContext)
{
// ** need access to service instance here **
return _next(httpContext);
}
}
有人在[45:30]的服务结构团队中提到了在WebAPI 2中使用TinyIoC来实现这一点。以及目前推荐的方法是使用asp.net内核
任何帮助或例子都将不胜感激 通过构造函数的依赖注入适用于中间件类以及其他类。只需向中间件构造函数添加其他参数
public MyMiddleware(RequestDelegate next, IMyService myService)
{
_next = next;
...
}
但是也可以直接将依赖项添加到Invoke
方法中
:因为中间件是在应用程序启动时构造的,而不是每个请求,所以在每个请求期间,中间件构造函数使用的作用域生存期服务不会与其他依赖注入类型共享。如果必须在中间件和其他类型之间共享作用域服务,请将这些服务添加到Invoke方法的签名中。Invoke
方法可以接受由依赖项注入填充的其他参数
在创建
ServiceInstanceListener
的asp.net核心无状态服务中,您可以像这样插入上下文:
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new[]
{
new ServiceInstanceListener(serviceContext =>
new WebListenerCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
{
logger.LogStatelessServiceStartedListening<WebApi>(url);
return new WebHostBuilder().UseWebListener()
.ConfigureServices(
services => services
.AddSingleton(serviceContext) // HERE IT GOES!
.AddSingleton(logger)
.AddTransient<IServiceRemoting, ServiceRemoting>())
.UseContentRoot(Directory.GetCurrentDirectory())
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
.UseStartup<Startup>()
.UseUrls(url)
.Build();
}))
};
}
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext httpContext, StatelessServiceContext serviceContext)
{
// ** need access to service instance here **
return _next(httpContext);
}
}
有关完整示例,请查看此存储库:
您的兴趣点:
- 设置DI:
- 在中间件中使用上下文:
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext httpContext, StatelessServiceContext serviceContext)
{
// ** need access to service instance here **
return _next(httpContext);
}
}