Castle Windsor IOC: Passing constructor parameters to child components

后端 未结 3 1780
臣服心动
臣服心动 2020-12-06 07:41

The following code is for demo purposes only.

Lets say i have 2 components (businessService, and dataService), and a UI class.

UI class needs a busi

3条回答
  •  离开以前
    2020-12-06 08:30

    I have needed to do this when creating transient components that require a context object. The solution I used was to override the DefaultDependencyResolver class so that it does pass inline arguments down the resolution pipeline.

    public class ArgumentPassingDependencyResolver : DefaultDependencyResolver
    {
        protected override CreationContext RebuildContextForParameter(
            CreationContext current, Type parameterType)
        {
            if (parameterType.ContainsGenericParameters)
            {
                // this behaviour copied from base class
                return current;
            }
    
            // the difference in the following line is that "true" is passed
            // instead of "false" as the third parameter
            return new CreationContext(parameterType, current, true);
        }
    }
    

    An instance of this class needs to be passed in when the container is created (other classes also need to be passed in because there's no convenient constructor that only takes a dependency resolver):

    var container = new WindsorContainer(
        new DefaultKernel(
            new ArgumentPassingDependencyResolver(),
            new NotSupportedProxyFactory()),
        new DefaultComponentInstaller());
    

提交回复
热议问题