Ninject Conventions with Ninject Factory Extension To Bind Multiple Types To One Interface

前端 未结 1 673
终归单人心
终归单人心 2021-01-23 09:00

I\'m trying to expand on the scenario asked in the SO question titled Ninject Factory Extension Bind Multiple Concrete Types To One Interface by using Ninject Conventions for c

相关标签:
1条回答
  • 2021-01-23 09:40

    Looks like, you have to define binding differently and provide your custom implementation of IBindingGenerator for this case

    Binding

    All implementation of ICar will have custom binding

    Kernel.Bind(scanner => scanner
                                .FromThisAssembly()
                                .SelectAllClasses()
                                .InheritedFrom<ICar>()
                                .BindWith(new BaseTypeBindingGenerator<ICar>()));
    

    Custom IBindingGenerator implementation

    Searching for all implementations of interface and bind them by type name

    public class BaseTypeBindingGenerator<InterfaceType> : IBindingGenerator
    {
        public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
        {
            if (type != null && !type.IsAbstract && type.IsClass && typeof(InterfaceType).IsAssignableFrom(type))
            {          
                yield return bindingRoot.Bind(typeof(InterfaceType))
                                        .To(type)
                                        .Named(type.Name) as IBindingWhenInNamedWithOrOnSyntax<object>;
            }
        }
    

    ps: here is a full sample

    0 讨论(0)
提交回复
热议问题