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

回眸只為那壹抹淺笑 提交于 2019-12-02 04:55:00

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!