我有一个实现自定义中间件的Service Fabric asp.net核心无状态服务。在中间件中,我需要访问我服务实例。我该如何使用asp.net内核的内置DI/IoC系统来注入它呢?
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);
}
}
有人提到在WebApi2中使用TinyIoC来实现这一点
2017年4月20日Q&A #11
45:30
与服务交换矩阵团队合作。以及当前推荐的方法是使用asp.net核心。
如有任何帮助或例子,我们将不胜感激!
发布于 2017-04-22 10:20:23
在asp.net核心无状态服务中创建
您可以像这样注入上下文:
protected override IEnumerable CreateServiceInstanceListeners()
{
return new[]
{
new ServiceInstanceListener(serviceContext =>
new WebListenerCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
{
logger.LogStatelessServiceStartedListening(url);
return new WebHostBuilder().UseWebListener()
.ConfigureServices(
services => services
.AddSingleton(serviceContext) // HERE IT GOES!
.AddSingleton(logger)
.AddTransient())
.UseContentRoot(Directory.GetCurrentDirectory())
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
.UseStartup()
.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);
}
}
有关完整的示例,请查看此存储库:
https://github.com/DeHeerSoftware/Azure-Service-Fabric-Logging-And-Monitoring
您的兴趣点:
设置DI:
https://github.com/DeHeerSoftware/Azure-Service-Fabric-Logging-And-Monitoring/blob/master/src/WebApi/WebApi.cs
在中间件中使用上下文:
https://github.com/DeHeerSoftware/Azure-Service-Fabric-Logging-And-Monitoring/blob/master/src/ServiceFabric.Logging/Middleware/RequestTrackingMiddleware.cs
发布于 2017-04-22 05:51:22
通过构造函数进行依赖注入对中间件类和其他类都有效。只需向中间件构造函数添加额外的参数
public MyMiddleware(RequestDelegate next, IMyService myService)
{
_next = next;
...
}
但是
还可以将依赖项直接添加到
方法
文档
:因为中间件是在应用程序启动时构造的,而不是按请求构造的,所以在每次请求期间,中间件构造函数使用的作用域生命周期服务不会与其他依赖项注入类型共享。如果您必须在中间件和其他类型之间共享作用域服务,请将这些服务添加到调用方法的签名中。The The The
方法可以接受由依赖项注入填充的附加参数。
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext, IMyScopedService svc)
{
svc.MyProperty = 1000;
await _next(httpContext);
}
}
https://stackoverflow.com/questions/43552441
复制相似问题