interface IUserService
class LocalUserService : IUserService
class RemoteUserService : IUserService
interface IUserRepository
class UserRepository : IUserRepository
如果我有以下接口(interface)和类,其中 IUserService
类依赖于 IUserRepository
。我可以通过执行以下操作来注册这些组件:
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)和类:
interface IUserService
class UserService : IUserService
interface IUserRepository
class WebUserRepository : IUserRepository
class LocalUserRepository : IUserRepository
class DBUserRepository : IUserRepository
如何注册这些组件,以便 IUserService
组件可以“选择”在运行时注入(inject)哪个存储库?我的想法是允许用户通过提供 3 个单选按钮(或其他按钮)来选择要查询的存储库,并要求容器每次解析一个新的 IUserService
。
最佳答案
如果您想决定注入(inject)(推送)哪个组件,请使用 IHandlerSelector
。
如果您想决定提取哪个组件,请使用 TypedFactoryFacility。
并作为旁注。
不要使用AddComponent
,使用container.Register(Component.For...)
关于dependency-injection - 温莎城堡注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2830278/