温莎城堡登记
interface IUserService
class LocalUserService : IUserService
class RemoteUserService : IUserService
interface IUserRepository
class UserRepository : IUserRepository
如果我有以下接口和类,其中 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 IUserService
class UserService : IUserService
interface IUserRepository
class WebUserRepository : IUserRepository
class LocalUserRepository : IUserRepository
class DBUserRepository : IUserRepository
如何注册这些组件以便 IUserService
组件可以“选择”在运行时注入哪个存储库?我的想法是允许用户通过提供 3 个单选按钮(或其他按钮)来选择要查询的存储库,并要求容器每次解析一个新的 IUserService
。
interface IUserService
class LocalUserService : IUserService
class RemoteUserService : IUserService
interface IUserRepository
class UserRepository : IUserRepository
If I have the following interfaces and classes, where the IUserService
classes have a dependency on IUserRepository
. I can register these components by doing something like:
container.AddComponent("LocalUserService", typeof(IUserService), typeof(LocalUserService));
container.AddComponent("RemoteUserService", typeof(IUserService), typeof(RemoteUserService));
container.AddComponent("UserRepository", typeof(IUserRepository), typeof(UserRepository));
... and get the service I want by calling:
IUserService userService = container.Resolve<IUserService>("RemoteUserService");
However, if I have the following interfaces and classes:
interface IUserService
class UserService : IUserService
interface IUserRepository
class WebUserRepository : IUserRepository
class LocalUserRepository : IUserRepository
class DBUserRepository : IUserRepository
How do I register these components so that the IUserService
component can "choose" which repository to inject at runtime? My idea is to allow the user to choose which repository to query from by providing 3 radio buttons (or whatever) and ask the container to resolve a new IUserService
each time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想决定注入(推送)哪个组件,您可以使用 IHandlerSelector。
如果您想决定提取哪个组件,请使用 TypedFactoryFacility。
并作为旁注。
不要使用
AddComponent
,使用container.Register(Component.For...)
If you want to decide which component to inject (push) you use
IHandlerSelector
s.If you want to decide which component to pull you use TypedFactoryFacility.
and as a sidenote.
Don't use
AddComponent
, usecontainer.Register(Component.For...)