代码之家  ›  专栏  ›  技术社区  ›  ladenedge

在StructureMap中使用开放泛型的自定义构造

  •  1
  • ladenedge  · 技术社区  · 14 年前

    我有一个典型的存储库界面, IRepository<T> ,还有很多混凝土仓库。大多数具体存储库如下所示:

    class ConcreteRepository<T> : IRepository<T> { .. }
    

    这些很容易注册到StructureMap:

    For(typeof(IRepository<>)).Use(typeof(ConcreteRepository<>));
    

    但是,我选择的一些具体存储库如下所示:

    class AbnormalRepository<T1, T2> : IRepository<T1>, IAbnormal<T2> { .. }
    

    i假设<T> s、 因此,对于这些,我目前正在使用特殊规则:

    // this sucks!
    For(typeof(IRepository<Foo1>)).Use(typeof(AbnormalRepository<Foo1, Bar1>));
    For(typeof(IRepository<Foo2>)).Use(typeof(AbnormalRepository<Foo2, Bar2>));
    

    如果我能指定一个StructureMap可以用来构造我的存储库的函数就好了,因为我知道我所有的异常存储库都实现了 IAbnormal<T> . 有什么想法吗?

    2 回复  |  直到 14 年前
        1
  •  2
  •   Community CDub    8 年前

    StructureMap IRegistrationConvention to register non default naming convention?

    您还可以在StructureMap源代码中看到许多IRegistrationConvention示例。

        2
  •  1
  •   Tim Hoolihan    14 年前

    // lambda with no params
    For<IRepository<Foo1>>().Use(() => { ... });
    // context is a StructureMap SessionContext
    For<IRepository<Foo1>>().Use(context => { ... }); 
    

    要查看SessionContext外的可用内容,请签出 http://structuremap.github.com/structuremap/UsingSessionContext.htm

    补充:

    using System;
    using NUnit.Framework;
    using StructureMap;
    
    namespace SMTest2
    {
        public interface IRepository<T> {}
        public class AbnormalRepository<T,T2> : IRepository<T>{ }
    
        [TestFixture]
        public class TestOpenGeneric
        {
            private IContainer _container   ;
    
            [SetUp]
            public void DescribeContainer()
            {
                _container = new Container(cfg => 
                    cfg.For(typeof (IRepository<>)).Use(ctx => new AbnormalRepository<String, int>()));
            }
    
            [Test]
            public void TestItWorks()
            {
                var stringVector = _container.GetInstance(typeof (IRepository<>));
                Assert.IsInstanceOf<AbnormalRepository<String,int>>(stringVector);
            }
        }
    }