利用 AllTypes.FromAssemblyContaining() / UsingFactoryMethod()

发布于 2024-11-07 22:24:18 字数 771 浏览 4 评论 0原文

我使用以下代码注册位于同一程序集中的许多存储库:

IoCContainer.Register(AllTypes.FromAssemblyContaining<RepositoryOne>).BasedOn(typeof(IRepository<>)).WithService.AllInterfaces().Configure(c => c.LifeStyle.Singleton));

因为我想影响这些存储库的创建,所以我尝试对其使用UsingFactoryMethod()。当我单独注册每个存储库时,使用此方法很简单,例如

IoCContainer.Register(Component.For<IRepositoryOne>().ImplementedBy<RepositoryOne>().LifeStyle.Singleton.UsingFactoryMethod(() => Factory.New<RepositoryOne>()));
...
IoCContainer.Register(Component.For<IRepositoryN>().ImplementedBy<RepositoryN>().LifeStyle.Singleton.UsingFactoryMethod(() => Factory.New<RepositoryN>()));

但是如何将UsingFactoryMethod()与第一个示例中的代码一起使用?

TIA

I am registering many repositories which are located in the same assembly by using the following code:

IoCContainer.Register(AllTypes.FromAssemblyContaining<RepositoryOne>).BasedOn(typeof(IRepository<>)).WithService.AllInterfaces().Configure(c => c.LifeStyle.Singleton));

Because I want to have influence on the creation of these repositories, I am trying to use UsingFactoryMethod() with it. Using this method is simple when I register every repository separately like

IoCContainer.Register(Component.For<IRepositoryOne>().ImplementedBy<RepositoryOne>().LifeStyle.Singleton.UsingFactoryMethod(() => Factory.New<RepositoryOne>()));
...
IoCContainer.Register(Component.For<IRepositoryN>().ImplementedBy<RepositoryN>().LifeStyle.Singleton.UsingFactoryMethod(() => Factory.New<RepositoryN>()));

But how can I use UsingFactoryMethod() together with the code from the first example?

TIA

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

灵芸 2024-11-14 22:24:18

您必须使用一些反射来使用它,因为您没有要解析的对象的确切类型。

var factoryMethod = typeof(Factory).GetMethod("New", BindingFlags.Static|BindingFlags.Public);

container.Register(
   AllTypes.FromAssemblyContaining<RepositoryOne>)
      .BasedOn(typeof(IRepository<>))
      .WithService.AllInterfaces()
      .Configure(x => x.UsingFactoryMethod((k, c) => factoryMethod.MakeGenericMethod(c.RequestedType).Invoke(null, null)));

You have to use a bit of reflection to use it, since you don't have the exact type of the object you'd be resolving.

var factoryMethod = typeof(Factory).GetMethod("New", BindingFlags.Static|BindingFlags.Public);

container.Register(
   AllTypes.FromAssemblyContaining<RepositoryOne>)
      .BasedOn(typeof(IRepository<>))
      .WithService.AllInterfaces()
      .Configure(x => x.UsingFactoryMethod((k, c) => factoryMethod.MakeGenericMethod(c.RequestedType).Invoke(null, null)));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文