vc 74
vc 74

Reputation: 38179

NInject equivalent of Autofac's AsClosedTypesOf

What is the NInject equivalent of the following code that uses Autofac:

var builder = new ContainerBuilder();

System.Reflection.Assembly assembly = ...;
builder.RegisterAssemblyTypes(assembly).AsClosedTypesOf(typeof(OpenGeneric<>))
                                       .As<IAnInterface>();

var resolved = container.Resolve<IEnumerable<IAnInterface>>();

Upvotes: 5

Views: 890

Answers (1)

Remo Gloor
Remo Gloor

Reputation: 32725

Using Ninject 3.0.0-rc3 you can use

kernel.Bind(
      x => x.FromThisAssembly()
            .SelectAllClasses().InheritedFrom(typeof(BaseService<>)).WhichAreGeneric()
            .BindToAllInterfaces());

Depending on your requirements you can probably remove the WhichAreGeneric statement. .SelectAllClasses().InheritedFrom(typeof(BaseService<>)).WhichAreGeneric() selects the classes to which a binding is created.

Conventions ensures that the interface and the implementation class must have the same open type arguments. E.g. In case

interface IBar<T1, T2>
interface IBaz<T>
interface IFoo
class Bar<T1, T2> : IBar<T1, T2>, IBaz<T1>, IFoo
class Foo : IBar<int, int>, IFoo

IBar<T1, T2> is the only valid interface for Bar<T1, T2>. But for Foo both IBar<int, int>, IFoo are valid.

Upvotes: 2

Related Questions