解决依赖于IList的城堡类型的问题

时间:2011-01-02 19:24:52

标签: castle-windsor

我正在尝试解析一个对象(Context类),它对IList有构造函数依赖,但我无法解析(请参阅下面的例外)。谁能解释为什么会这样?城堡和.net通用例外是否存在问题?感谢您的回复

public class Context : IContext
    {

        public Context(
            IApplicationSite applicationSite,
            IList<Currency> currencies)
        {
        }
    }

这是我的IOC注册:

var _container = new WindsorContainer();

_container.Kernel.AddFacility<FactorySupportFacility>();            

    _container.Register(
    Component.For<IRepository>()
    .ImplementedBy<Repository>()
    .Named("repository"));

_container.Register(
    Component
    .For<IList<Currency>>()
    .UsingFactoryMethod(kernel => kernel.Resolve<IRepository>().GetCurrencies())
    .Named("currencies"));

_container.Register(
    Component
    .For<IApplicationSite>()
    .UsingFactoryMethod(kernel => kernel.Resolve<IRepository>().GetApplicationSite())
    .Named("applicationSite"));

_container.Register(
    Component.For<IContext>()
    .ImplementedBy<Context>()
    .Named("Context"));

var _context = _container.Resolve<IContext>();

当我尝试解决上下文时,我得到以下异常:

Castle.MicroKernel.Resolvers.DependencyResolverException : Could not resolve non-optional dependency for 'Context' (ClassLibraryCastle.Context). 
Parameter 'currencies' type 'System.Collections.Generic.IList`1[[ClassLibraryCastle.Currency, ClassLibraryCastle, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'

1 个答案:

答案 0 :(得分:0)

我找到了一种解决依赖于IList的方法 - 使用动态参数

_container.Register(
    Component.For<IContext>()
        .ImplementedBy<Context>()
        .Named("context")
        .DynamicParameters((k, parameters) => // dynamic parameters
        {
           parameters["currencies"] = k.Resolve<IList<Currency>>();
        }));