有没有更好的方法来使用温莎城堡的工厂 API?

发布于 2024-08-24 07:49:46 字数 832 浏览 5 评论 0原文

我对其他 IoC 容器持开放态度,例如 NInject 和 StructureMap,如果它们比这干净得多。我听说 StructureMap 刚刚引入了“容器”,可以简化这个过程,也许?

正如标题所说,有更好的方法吗?这看起来像是很多代码,只是为了注册一个需要工厂来创建它的对象。

// The process to register an object, with a factory method
var cfg = new MutableConfiguration(p.Name);
cfg.Attributes["factoryId"] = p.TypeFactory.Name;
cfg.Attributes["factoryCreate"] = "Create";
var model = _container.Kernel.ComponentModelBuilder.BuildModel(
    p.Name, p.TypeService, p.Type, null);
model.LifestyleType = LifestyleType.Pooled;
model.Configuration = cfg;
_container.Kernel.AddCustomComponent(model);

与添加组件的“非工厂”方式不同:

// registering a component with no factory method
_container.AddComponentLifeStyle(
    p.Name, p.TypeService, p.Type, LifestyleType.Singleton);

第一种方式似乎过于复杂。

提前致谢!

I am open to other IoC containers, such as NInject and StructureMap if they are much cleaner than this. I hear that StructureMap just introduced "containers" that may simplify this , perhaps?

As the title says, is there a better way? This seems like a lot of code, just to register an object that requires a factory to create it.

// The process to register an object, with a factory method
var cfg = new MutableConfiguration(p.Name);
cfg.Attributes["factoryId"] = p.TypeFactory.Name;
cfg.Attributes["factoryCreate"] = "Create";
var model = _container.Kernel.ComponentModelBuilder.BuildModel(
    p.Name, p.TypeService, p.Type, null);
model.LifestyleType = LifestyleType.Pooled;
model.Configuration = cfg;
_container.Kernel.AddCustomComponent(model);

Versas the "non-factory" way of adding a component:

// registering a component with no factory method
_container.AddComponentLifeStyle(
    p.Name, p.TypeService, p.Type, LifestyleType.Singleton);

The first seems overly complex.

Thanks in advance!

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

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

发布评论

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

评论(1

知足的幸福 2024-08-31 07:49:46

我不确定您要注册什么(第一个代码块中的 p 是什么?),但是使用 UsingFactoryMethod,工厂注册轻而易举。示例代码:

container.AddFacility<FactorySupportFacility>()
   .Register(
      Component.For<IMyService>()
         .UsingFactoryMethod(() => MyLegacyServiceFactory.CreateMyService())
         .LifeStyle.Pooled
   );

I'm not sure what you're trying to register (what's p in the first code block?) but with UsingFactoryMethod, factory registration is a breeze. Sample code:

container.AddFacility<FactorySupportFacility>()
   .Register(
      Component.For<IMyService>()
         .UsingFactoryMethod(() => MyLegacyServiceFactory.CreateMyService())
         .LifeStyle.Pooled
   );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文