How do I connect the various pieces of my Web API Castle Windsor DI code?

后端 未结 3 1744
离开以前
离开以前 2021-01-13 23:55

How do I connect the various pieces of my Web API Castle Windsor DI code so that the Controller\'s routing selects the correct interface implementation?

Note

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-14 00:50

    You should not mix installation vs resolving. IOW your should not have

    kernel.AddFacility();
    

    in the WindsorControllerFactory

    But the generic container configuration such registering TypedFactoryFacility should be executed in an installer called as earlier as possible.

    In order to drive installer execution, you should use an Installer factory

    public class YourInstallerFactory : InstallerFactory
    {
        public override IEnumerable Select(IEnumerable installerTypes)
        {
            var windsorInfrastructureInstaller = installerTypes.FirstOrDefault(it => it == typeof(WindsorInfrastructureInstaller));
    
            var retVal = new List();
            retVal.Add(windsorInfrastructureInstaller);
            retVal.AddRange(installerTypes
                .Where(it =>
                    typeof(IWindsorInstaller).IsAssignableFrom(it) &&
                    !retVal.Contains(it)
                    ));
    
            return retVal;
        }
    }
    

    Where windsorInfrastructureInstaller will be somenthing like this

    public class WindsorInfrastructureInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            // Resolvers
            //container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel));
    
            // TypedFactoryFacility
            container.AddFacility();
        }
    }
    

    In your global.asax you'll create&use you installer factory as following

     var installerFactory = new YourInstallerFactory();
     container.Install(FromAssembly.This(installerFactory));
    

    Your "FrontEnd"(for example the mvc/webapi) project has a folder containing all installers(WindsorInfrastructureInstaller will be one of those) and the installer factory as well or at least that's the way I'm use to organize my solution.

提交回复
热议问题