Ninject工厂扩展的Ninject约定将多种类型绑定到一个接口

时间:2013-04-07 22:54:12

标签: inversion-of-control factory ninject-extensions ninject-3 ninject-conventions

我正在尝试通过使用Ninject约定来实现ICar实现的基于约定的绑定来扩展标题为Ninject Factory Extension Bind Multiple Concrete Types To One Interface的SO问题中提出的场景。

我正在使用the accepted answer authored by Akimhis Gist来概述完整的示例。

不同之处在于我已经用基于约定的绑定替换了显式ICar绑定(或尝试使用它,至少;)

public class CarModule : NinjectModule
{
    public override void Load()
    {
        Bind<ICarFactory>()
            .ToFactory(() => new UseFirstArgumentAsNameInstanceProvider());

        // my unsuccessful binding
        Kernel.Bind(scanner => scanner
                        .FromThisAssembly()
                        .SelectAllClasses()
                        .InheritedFrom<ICar>()
                        .BindAllInterfaces());
        //Bind<ICar>()
        //    .To<Mercedes>()
        //    .Named("Mercedes");
        //Bind<ICar>()
        //    .To<Ferrari>()
        //    .Named("Ferrari");
    }
}

当我尝试在测试中实例化car变量时,我得到ActivationException

Ninject.ActivationException was unhandled by user code
  Message=Error activating ICar
No matching bindings are available, and the type is not self-bindable.
Activation path:
  1) Request for ICar

Suggestions:
  1) Ensure that you have defined a binding for ICar.
  2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
  3) Ensure you have not accidentally created more than one kernel.
  4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
  5) If you are using automatic module loading, ensure the search path and filters are correct.

  Source=Ninject
  StackTrace:
       at Ninject.KernelBase.Resolve(IRequest request) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 362
       at Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 263
       at Ninject.ResolutionExtensions.Get(IResolutionRoot root, Type service, String name, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 164
       at Ninject.Extensions.Factory.Factory.InstanceResolver.Get(Type type, String name, Func`2 constraint, ConstructorArgument[] constructorArguments, Boolean fallback) in c:\Projects\Ninject\ninject.extensions.factory\src\Ninject.Extensions.Factory\Factory\InstanceResolver.cs:line 75
       at Ninject.Extensions.Factory.StandardInstanceProvider.GetInstance(IInstanceResolver instanceResolver, MethodInfo methodInfo, Object[] arguments) in c:\Projects\Ninject\ninject.extensions.factory\src\Ninject.Extensions.Factory\Factory\StandardInstanceProvider.cs:line 78
       at Ninject.Extensions.Factory.FactoryInterceptor.Intercept(IInvocation invocation) in c:\Projects\Ninject\ninject.extensions.factory\src\Ninject.Extensions.Factory\Factory\FactoryInterceptor.cs:line 57
       at Castle.DynamicProxy.AbstractInvocation.Proceed()
       at Castle.Proxies.ICarFactoryProxy.CreateCar(String carType)
       at Ninject.Extensions.Conventions.Tests.NinjectFactoryTests.A_Car_Factory_Creates_A_Car_Whose_Type_Name_Equals_Factory_Method_String_Argument() in C:\Programming\Ninject.Extensions.Conventions.Tests\NinjectFactoryTests.cs:line 33
  InnerException: 

如何通过此测试?

[Fact]
public void A_Car_Factory_Creates_A_Car_Whose_Type_Name_Equals_Factory_Method_String_Argument()
{
    // auto-module loading is picking up my CarModule - otherwise, use:
    // using (StandardKernel kernel = new StandardKernel(new CarModule()))
    using (StandardKernel kernel = new StandardKernel())
    {
        // arrange
        string carTypeArgument = "Mercedes";
        ICarFactory factory = kernel.Get<ICarFactory>();

        // act
        var car = factory.CreateCar(carTypeArgument);

        // assert
        Assert.Equal(carTypeArgument, car.GetType().Name);
    }
}

这是代码的其余部分,尽可能浓缩,这样您就不必参考original question

public interface ICarFactory { ICar CreateCar(string carType); }

public interface ICar { void Drive(); void Stop(); }

public class Mercedes : ICar {
    public void Drive() { /* mercedes drives */ }
    public void Stop() { /* mercedes stops */ }
}

public class Ferrari : ICar {
    public void Drive() { /* ferrari drives */ }
    public void Stop() { /* ferrari stops */ }
}

public class UseFirstArgumentAsNameInstanceProvider : StandardInstanceProvider
{
    protected override string GetName(MethodInfo methodInfo, object[] arguments)
    {
        return (string) arguments[0];
    }

    protected override ConstructorArgument[] GetConstructorArguments(MethodInfo methodInfo, object[] arguments)
    {
        return base.GetConstructorArguments(methodInfo, arguments).Skip(1).ToArray();
    }
}

1 个答案:

答案 0 :(得分:1)

看起来,您必须以不同方式定义绑定,并为此案例提供IBindingGenerator的自定义实现

装订

ICar的所有实施都将具有自定义绑定

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

自定义IBindingGenerator实施

搜索接口的所有实现并按类型名称

绑定它们
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:这是full sample