Ninject Binding by Convention not working with generics types

纵饮孤独 提交于 2019-12-12 14:11:52

问题


I am using .NET 4.5, Ninject 3 with the binding by convention lib as follow:

kernel.Bind(x => x
    .FromAssembliesMatching("assembly.dll")
    .SelectAllClasses().InheritedFrom(typeof(ICommandHandler<>))
    .BindAllInterfaces());

And this is binding properly for:

public class MyCommandHandler : ICommandHandler<MyCommand>

But doesn't bind:

public class MyGenericCommandHandler<T> : ICommandHandler<MyGenericCommand<T>>

However, the previous binding works if I add individual bindings for specific implementation of my generics class, such as:

kernel.Bind(typeof(ICommandHandler<MyGenericCommand<float>>))
      .To(typeof(MyGenericCommandHandler<float>))
kernel.Bind(typeof(ICommandHandler<MyGenericCommand<int>>))
      .To(typeof(MyGenericCommandHandler<int>))

But adding each individual generic type defeats the purpose of conventions and require adding binding for each possible individual type such as float, int, string, etc...

Do you know how to modify the convention or add another one (or even come with a completely different solution) to support the generic version of my command? i.e. supporting two-level generics.


回答1:


EDIT: Doesn't compile [and the fact it doesn't reveals the requirement doesn't make sense], see reasoning for this conclusion in the comments.


This is just the normal open generics case. As alluded to with a link in my earlier comment, the way a basic bind to make that DRY looks is simply:

kernel.Bind(typeof(ICommandHandler<MyGenericCommand<>>))
    .To(typeof(MyGenericCommandHandler<>));

This binding will then suffice for any T variant of ICommandHandler<MyGenericCommand<T>>.

In the context of doing convention based binding it to mapping what you're expecting, the problem is that SelectAllClasses().InheritedFrom(typeof(ICommandHandler<>)) does not include generic classes -- this makes sense as it's rare that you can specify generalized rules on non concrete classes.

You can either

  • use a different Projection portion of the DSL to select the Generic classes and then bind them in some convention based manner
  • expose a NinjectModule from assemblies exposing [open] generic services which does the above Bind and then do a kernel.Load() of the module [prob by the DLL name pattern].


来源:https://stackoverflow.com/questions/16764603/ninject-binding-by-convention-not-working-with-generics-types

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