c# – NInject相当于Autofac的AsClosedTypesOf

使用Autofac的以下代码的NInject等价物是什么:

var builder = new ContainerBuilder();

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

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

最佳答案 使用Ninject 3.0.0-rc3即可使用

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

根据您的要求,您可以删除WhichAreGeneric语句. .SelectAllClasses().InheritedFrom(typeof(BaseService<>)).WhichAreGeneric()选择创建绑定的类.

约定确保接口和实现类必须具有相同的开放类型参数.例如.如果

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> Bar是< T1,T2>的唯一有效接口.但是对于Foo而言,IBar< int,int>,IFoo都是有效的.

点赞