[英]AutoFac constructor multiple Interface
我在我的項目中使用Autofac。 我想使用一個簡單的界面來解決它們。 不是通用存儲庫。
我在舊項目中使用Castle。 它有一個具有靜態方法的類。 我在這樣的構造函數方法中使用了它;
IService.ProductService.GetMyProducts();
在Autofac中,我找不到上述任何內容。 請幫我。 我不想在構造函數中使用很多接口。
private IGeneralRepository generalRep;
private IDenemeRepository denemeRep;
private IGokberkRepository GokberkRep;
public HomeController(IDenemeRepository dr,IGokberkRepository gr, IGeneralRepository ger)
{
generalRep = ger;
denemeRep = dr;
GokberkRep = gr;
}
我可以想到兩種減少構造器中注入服務數量的方法。
首先 ,在Autofac中,您可以擁有一個類型為IComponentContext
參數,並且當您從容器實例解析服務時, IComponentContext
依賴關系將自動解析為容器實例。 然后,您可以從中解決其余的依賴關系:
// constructor of your component
public MyComponent(IComponentContext components)
{
_serviceA = components.Resolve<IServiceA>();
_serviceB = components.Resolve<IServiceB>();
}
順便說一句,在溫莎城堡中,您必須顯式注冊該容器的實例才能使上述方法起作用。
第二種方法是創建一個“復合”服務,其中包含應用程序需要的所有(或最常見的)服務。 然后注入該服務並從中獲取所有其他服務:
// composite service - implement this interface as shown below
public interface ICommonServices
{
IServiceA ServiceA { get; }
IServiceB ServiceB { get; }
}
組合服務實現:
// a class that implements ICommonServices interface
public class CommonServices : ICommonServices
{
public CommonServices(IServiceA serviceA, IServiceB serviceB)
{
this.ServiceA = serviceA;
this.ServiceB = serviceB;
}
public IServiceA ServiceA { get; private set; }
public IServiceB ServiceB { get; private set; }
}
請注意,您必須在容器中注冊復合服務和內部服務。
現在,您的構造函數中只能有一個參數:
public MyComponent(ICommonServices services)
{
_services = services;
}
使用內部服務:
public void SomeMethod()
{
_services.ServiceA.DoSomething();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.