2016-11-19 219 views
2
  • 我使用ASP.NET核心
  • IService與DI容器註冊
  • 有兩種實現方式:FooServiceBarService
  • 我必須選擇基於當前請求的MVC區服務

所以,我需要這樣的東西:確定ASP.NET MVC核心區

services.AddScoped<IService>(
    c => IsThisTheFooArea 
     ? c.GetRequiredService<FooService>() as IService 
     : c.GetRequiredService<BarService>() as IService 
); 

我不知道如何執行IsThisTheFooArea檢查。

我如何訪問HttpContext或類似的東西,所以我可以檢查當前的路線?

回答

2

這裏有一個辦法:

ConfigureServices.cs:

 services.AddSingleton<IActionContextAccessor, ActionContextAccessor>(); 
     services.AddScoped<IService>(provider => 
     { 
      var actionContextAccessor = provider.GetService<IActionContextAccessor>(); 
      var descriptor = actionContextAccessor.ActionContext.ActionDescriptor as ControllerActionDescriptor; 
      var areaName = descriptor.ControllerTypeInfo.GetCustomAttribute<AreaAttribute>().RouteValue; 
      if(areaName == "FooArea") 
      { 
       return new FooService(); 
      } 
      else 
      { 
       return new BarService(); 
      } 
     }); 

服務:

public interface IService { string DoThisThing(); } 

public class FooService : IService 
{ 
    public string DoThisThing() 
    { 
     return "Foo"; 
    } 
} 

public class BarService : IService 
{ 
    public string DoThisThing() 
    { 
     return "Bar"; 
    } 
} 

和控制器:

[Area("FooArea")] 
public class FooController : Controller 
{ 
    private readonly IService _service; 

    public FooController(IService service) 
    { 
     _service = service; 
    } 

    public IActionResult Index() 
    { 
     return Content(_service.DoThisThing()); 
    } 
} 

[Area("BarArea")] 
public class BarController : Controller 
{ 
    private readonly IService _service; 

    public BarController(IService service) 
    { 
     _service = service; 
    } 

    public IActionResult Index() 
    { 
     return Content(_service.DoThisThing()); 
    } 
} 
+0

謝謝,這個工程。 (......但哇,這麼多的箍箭跳過了這麼簡單的事情。) – grokky

+0

另外,我回想起在github項目頁面上閱讀'ActionContextAccessor'默認沒有註冊,因爲它很昂貴,所以很遺憾沒有更簡單的方法它的工作原理雖然足夠滿足我的需求。 – grokky

+0

這是獲取區域信息所必需的。我不知道是否有另一種方式獲得地區名稱。可以使用請求路徑(區域部分),但在這種情況下,您需要注入'HttpContextAccessor',我認爲這不是好的方法。 –

-1

您需要實現(或基於IControllerFactory或IDependencyResolver查找實現),並在應用程序啓動時將其設置爲注入控制器依賴項。

ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory(container)); 

// Or... 

DependencyResolver.SetResolver(new MyDependencyResolver(container)); 

更多信息 https://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-dependency-injection

+1

這不是核心。另外,我不需要注入控制器。 – grokky