简体   繁体   English

查找使用Ninject实现通用接口的类

[英]Find class that implements generic interface with Ninject

With Ninject you can register a binding like this: 使用Ninject,您可以注册如下绑定:

Bind(typeof(IQueryHandler<,>)).To(typeof(QueryHandler<,>));

But in my case I don't know the name of the actual class. 但就我而言,我不知道实际班级的名称。 All i know is that it implements a certain interface. 我所知道的是它实现了特定的接口。

So for example, suppose I have the following: 因此,例如,假设我有以下内容:

public class CreatePageQueryHandler : IQueryHandler<CreatePage, string>
{
    public string Retrieve(CreatePage query)
    { ... }
}

There will be only one class that implements the interface with these gerenic params: IQueryHandler<CreatePage, string> 将只有一个类使用这些gerenic参数实现该接口: IQueryHandler<CreatePage, string>

Is there a way with Ninject to dynamically get an instance of the class? Ninject有没有办法动态获取类的实例? Something like: 就像是:

kernel.Get<IQueryHandler<CreatePage, string>>(); // returns instance of: CreatePageQueryHandler 

Please note: 请注意:

I don't want to manually bind this in the RegisterServices method. 我不想在RegisterServices方法中手动bind它。 I'm looking for a dynamic way to get the instance of the class. 我正在寻找一种获取类实例的动态方法。

Ninject contains a batch-registration API. Ninject包含一个批次注册API。 You can use the following binding for instance: 例如,您可以使用以下绑定:

kernel.Bind(
    x => x.FromAssembliesMatching("Fully.Qualified.AssemblyName*")
    .SelectAllClasses()
    .InheritedFrom(typeof(IQueryHandler<,>))
    .BindBase()
);

With this Code you will get all types which implements IQueryHandler. 通过此代码,您将获得实现IQueryHandler的所有类型。

var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(p => typeof(IQueryHandler).IsAssignableFrom(p));

After that you can register the types in Ninject or you can manually create a Instance from one of the Type: 之后,您可以在Ninject中注册类型,也可以从以下类型之一手动创建实例:

var instance = (IQueryHandler)Activator.CreateInstance(types.First());

I did not test this Code, on .Net Core there is a different way to get all types from an assembly 我没有测试此代码,在.Net Core上,有一种从装配中获取所有类型的方法

I think you need Ninject convention extensions. 我认为您需要Ninject约定扩展。

See https://github.com/ninject/Ninject.Extensions.Conventions 参见https://github.com/ninject/Ninject.Extensions.Conventions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM