温莎城堡登记

发布于 2024-09-01 02:59:22 字数 1139 浏览 5 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不气馁 2024-09-08 02:59:22

如果您想决定注入(推送)哪个组件,您可以使用 IHandlerSelector。

如果您想决定提取哪个组件,请使用 TypedFactoryFacility。

并作为旁注。

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

If you want to decide which component to inject (push) you use IHandlerSelectors.

If you want to decide which component to pull you use TypedFactoryFacility.

and as a sidenote.

Don't use AddComponent, use container.Register(Component.For...)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文