简体   繁体   中英

Find class that implements generic interface with Ninject

With Ninject you can register a binding like this:

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>

Is there a way with Ninject to dynamically get an instance of the class? 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. I'm looking for a dynamic way to get the instance of the class.

Ninject contains a batch-registration 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.

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:

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

I think you need Ninject convention extensions.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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