[英]Asp.net Core 2 - How to use ServiceLocator in Asp.net Core 2.0
我的Startup
是這樣的:
public void ConfigureServices(IServiceCollection services)
{
// code here
Bootstraper.Setup(services);
}
我的Bootstraper
類是這樣的:
public static partial class Bootstraper
{
// code here
public static IServiceCollection CurrentServiceCollection { get;set;}
public static IServiceProvider CurrentServiceProvider
{
get { return CurrentServiceCollection.BuildServiceProvider(); }
}
public static void Setup(IServiceCollection serviceCollection)
{
// code here
SetupLog();
InitializeCulture();
InitializeDbContexts();
RegisterDataModelRepositories();
}
這是我的RegisterDataModelRepositories()
:
CurrentServiceCollection.AddTransient<IDefAccidentGroupRepository>(p => new DefAccidentGroupRepository(ApplicationMainContextId));
CurrentServiceCollection.AddTransient<IDefGenderRepository>(p => new DefGenderRepository(ApplicationMainContextId));
簡而言之:我只想能夠在我的方法中使用Service Locator而不解決類構造函數中的依賴關系...有沒有解決的辦法...。
依賴項注入也可以基於操作進行。
將引用依賴注入到控制器中:使用FromServices進行動作注入
有時,您不需要為一個控制器內的多個動作提供服務。 在這種情況下,將服務作為操作方法的參數注入可能是有意義的。 這是通過使用屬性
[FromServices]
標記參數來完成的
public IActionResult SomeAction([FromServices] IReportService reports) {
//...use the report service for this action only
return View();
}
只需確保所需的服務已在服務集合中注冊即可。
services.AddTransient<IDefAccidentGroupRepository>(p => new DefAccidentGroupRepository(ApplicationMainContextId));
services.AddTransient<IDefGenderRepository>(p => new DefGenderRepository(ApplicationMainContextId));
services.AddTransient<IReportService, ReportService>().
好了,謝謝您的幫助。有一種更簡便更好的方法,我只需要添加另一個使用這些存儲庫的服務,然后在控制器中解析該服務,然后讓Asp.net Core 2.0 DI解決該問題即可。為了我 ...
public interface IActionService
{
IRepositoryA repA {get;set;}
IRepositoryB repB { get;set;}
DoTaskX();
DoTaskY();
}
然后在我的ActionService中:
public class ActionService : IActionService
{
public IRepositoryA repA {get;set;}
public IRepositoryB repB { get;set;}
public ActionService (IRepositoryA rep_a , IRepositoryB rep_b ) {
repA = rep_a;
repB = rep_b;
}
DoTaskX(){
// do task using repository A and B
}
}
然后我在Startup.cs中注冊IActionService並在我的ActionController中解決它,生活變得更加輕松,代碼變得更加干凈...
解決方案很容易,但是我不得不改變思維方式來解決問題...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.