有没有更好的方法来使用温莎城堡的工厂 API?
我对其他 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定您要注册什么(第一个代码块中的
p
是什么?),但是使用UsingFactoryMethod
,工厂注册轻而易举。示例代码:I'm not sure what you're trying to register (what's
p
in the first code block?) but withUsingFactoryMethod
, factory registration is a breeze. Sample code: