2
interface IUserService 
class LocalUserService : IUserService 
class RemoteUserService : IUserService 

interface IUserRepository 
class UserRepository : IUserRepository 

如果我有以下接口和類,其中IUserService類對IUserRepository有依賴關係。通過調用Castle windsor註冊

container.AddComponent("LocalUserService", typeof(IUserService), typeof(LocalUserService)); 
container.AddComponent("RemoteUserService", typeof(IUserService), typeof(RemoteUserService)); 
container.AddComponent("UserRepository", typeof(IUserRepository), typeof(UserRepository)); 

...並得到我想要的服務:我可以做這樣的事情註冊這些組件

IUserService userService = container.Resolve<IUserService>("RemoteUserService"); 

但是,如果我有以下的接口和類:

interface IUserService 
class UserService : IUserService 

interface IUserRepository 
class WebUserRepository : IUserRepository 
class LocalUserRepository : IUserRepository 
class DBUserRepository : IUserRepository 

如何註冊這些組件,以便IUserService組件可以「選擇」在運行時注入哪個存儲庫?我的想法是允許用戶通過提供3個單選按鈕(或任何)來選擇要查詢的存儲庫,並要求容器每次解析新的IUserService

回答

4

如果您要決定注入哪個組件(推送),請使用IHandlerSelector s。

如果您想決定使用TypedFactoryFacility的哪個組件。

並作爲旁註。

不要使用AddComponent,使用container.Register(Component.For...)

+0

有AddComponent和寄存器之間的區別嗎? – nivlam 2010-05-13 21:16:20

+0

主要區別在於Register更靈活,並且'AddComponent'將從下一個版本開始過時,並在稍後移除。 – 2010-05-14 06:07:07

相關問題