代码之家  ›  专栏  ›  技术社区  ›  Rob Allen

类库/dll中的structuremap引导

  •  3
  • Rob Allen  · 技术社区  · 16 年前

    使用structuremap引导dll的最佳方法是什么?我真的不希望库的用户自己配置任何东西,如果他们不想的话。我认为.config可能是最简单的,但是2.6.1已经过时了,我还不熟悉它的许多特性/变化。

    1 回复  |  直到 16 年前
        1
  •  5
  •   KevM    16 年前

    正如我在上面的评论中提到的,您可以使用工厂方法来确保StructureMap容器已启动,并准备好用于库中的顶级类。下面是一个例子。

    public interface ILibraryClass
    {
        void SomethingAwesome();
    }
    
    public class LibraryClass : ILibraryClass
    {
        public void SomethingAwesome()
        {
        }
    }
    
    public class API
    {
        private static IContainer _container;
    
        private static IContainer Container
        {
            get
            {
              if (_container == null) //TODO add locking around this for thread safety?
                 InitializeContainer();
    
              return _container;
            }
        }
    
        private static void InitializeContainer()
        {
            _container = new Container(config => { config.For<ILibraryClass>().Use<LibraryClass>(); });
        }
    
        public static ILibraryClass LibraryClass()
        {
            return Container.GetInstance<ILibraryClass>();
        }
     }
    
    [Test]
    public void library_factory_method()
    {
        API.LibraryClass().ShouldBeOfType<LibraryClass>();
    }