Resolving a list of components as a constructor argument
Say I have an interface to define formatting reports:
pu开发者_Go百科blic interface IFormatter
{
string Name {get;}
Report Format(InputData data);
}
and an implementation of a provider that will format reports for me:
public FormatterProvider : IFormatterProvider
{
private readonly IList<IFormatter> _formatter;
public FormatterProvider(IList<IFormatter> formatters)
{
_formatters = formatters;
}
public IFormatter GetFormatter(string name){ return _formatters.Where(x => x.Name == name); }
}
I know I can register all of the formatters in an assembly using this registration:
container.Register(
AllTypes.FromAssemblyName("MyCompany.Formatters")
.BasedOn<IFormatter>()
.WithService
.FromInterface()
);
But, how to I register the provider so that any formatters registered in the container are passed to it's constructor?
Use the subresolver called CollectionResolver.
Container.Kernel.Resolver.AddSubResolver(new CollectionResolver(Container.Kernel, true));
I think you will need to change the IList to IEnumerable to make this work, but not for sure on that.
精彩评论