2017-04-21 25 views
1

我有一個實現自定義中間件的服務結構asp.net核心無狀態服務。在那個中間件中我需要訪問我的服務實例。我將如何使用asp.net內核的內置DI/IoC系統注入這些內容?如何將Service Fabric服務上下文注入到asp.net核心中間件?

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); 
    } 
} 

有人提到在網絡API 2在Apr 20, 2017 Q&A #11 [45:30]與服務織物團隊完成這個使用TinyIoC。以及目前推薦的方法是使用asp.net核心。

任何幫助或例子將不勝感激!

回答

4

在創建該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); 
    } 
} 

有關完整示例,請查看此存儲庫:https://github.com/DeHeerSoftware/Azure-Service-Fabric-Logging-And-Monitoring

點你感興趣:

+0

正是我需要的 - 謝謝! – rktect

2

通過構造函數的依賴注入對中間件類以及其他類都起作用。只需添加額外的參數,以中間件構造

public MyMiddleware(RequestDelegate next, IMyService myService) 
{ 
    _next = next; 
    ... 
} 

也可以直接添加依賴於Invoke方法

Documentation:由於中間件在應用程序啓動構建,而不是每個請求,作用域中間件構造函數使用的生命週期服務在每個請求期間不與其他依賴注入類型共享。如果您必須在您的中間件和其他類型之間共享有限範圍的服務,請將這些服務添加到Invoke方法的簽名中。 Invoke方法可以接受由依賴注入填充的其他參數。

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); 
    } 
} 
+1

感謝完整的答案!我很抱歉,我不清楚我的問題在哪裏......我瞭解asp.net核心的DI模型,我的問題更多的是如何讓我的Startup.ConfigureServices中的Service Fabric服務實例注入它。 – rktect

相關問題