What conventions/idioms/patterns are you using configuring IOC Containers using the new Fluent Interfaces

后端 未结 4 1546
孤独总比滥情好
孤独总比滥情好 2021-02-06 11:13

I am in the middle of moving over a large body of code to Castle Trunk which includes the new fluent interface for configuring the container. Since the project has a huge windso

4条回答
  •  無奈伤痛
    2021-02-06 11:56

    I had a project where we were using Unity, and I watched a video about StructureMap and I liked the registration idea from the start.

    So I created the following interface:

    /// 
    /// An interface which must be implemented to create a configurator class for the UnityContainer.
    /// 
    public interface IUnityContainerConfigurator
    {
        /// 
        /// This method will be called to actually configure the container.
        /// 
        /// The container to configure.
        void Configure(IUnityContainer destination);
    }
    

    And have assemblies offer a default Configurator class. We've also wrapped our Unity IoC using a static class so that we can call IoC.Resolve, and I just added the following functions to that wrapper:

        /// 
        /// Configure the IoC
        /// 
        public static class Configure
        {
            /// 
            /// Configure the IoC using by calling the supplied configurator.
            /// 
            /// The configurator to use
            public static void From() where TConfigurator : IUnityContainerConfigurator, new()
            {
                From(new TConfigurator());
            }
            /// 
            /// Configure the IoC using by calling the supplied configurator.
            /// 
            /// The configurator instance to use
            public static void From(IUnityContainerConfigurator configurationInterface)
            {
                configurationInterface.Configure(instance);
            }
            // other configuration.
        }
    

    So in the initialization form either the program or the website I'd just call:

    IoC.Configure.From();
    

    In the BLL there is a class like this:

    public class DefaultMapping:IUnityContainerConfigurator
    {
        public void Configure(IUnityContainer destination)
        {
            destionation.RegisterType();
            // and more..
        }
    }
    

    The only downside is that all you're layers are coupled to the chosen IoC container.

    Update: Since this answer I have posted an article on my blog containing the Unity wrapper.

提交回复
热议问题