【问题标题】:How to define a Structuremap named instance in Code如何在代码中定义 Structuremap 命名实例
【发布时间】:2009-03-22 18:37:09
【问题描述】:

我想在代码中创建一个结构映射命名实例,没有配置文件

我希望能够像这样创建实例:

var namedInjector = ObjectFactory.GetNamedInstance<IInjectable>("Other");

我无法在代码中定义这种类型。我找到了this 样本 但它使用以前版本的旧语法并将命名实例定义为:

.ForRequestedType<MementoType>()
.AddConcreteType<ConcreteType>(instanceName)

在最新的结构映射版本中,没有采用实例名称的 .AddConcreteType(instanceName) 方法。

【问题讨论】:

    标签: .net structuremap


    【解决方案1】:

    我相信你需要这样的东西:

    class MyRegistry : Registry {
        public MyRegistry() {
            this.ForRequestedType<IFoo>()
                .TheDefaultIsConcreteType<Bar>()
                .AddInstances( x => {
                    x.OfConcreteType<Blap>().WithName("abc");
                });
        }
    }
    ...
    ObjectFactory.Configure(x=>x.AddRegistry<MyRegistry>());
    IFoo test1 = ObjectFactory.GetInstance<IFoo>(); // Bar
    IFoo test2 = ObjectFactory.GetNamedInstance<IFoo>("abc"); // Blap
    ...
    interface IFoo {}
    public class Bar : IFoo {}
    public class Blap : IFoo {}
    

    【讨论】:

    • 对 StructureMap 的新语法有什么想法吗?
    【解决方案2】:

    用新语法的话来说:

                For<IEncryptionService>()
                    .AddInstances(x => { x.OfConcreteType<AdvancedEncryptionService>().Named("Advanced"); })
                    .Use<EncryptionService>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多