vc *_* 74 5 c# ninject autofac
以下使用 Autofac 的代码的 NInject 等效项是什么:
var builder = new ContainerBuilder();
System.Reflection.Assembly assembly = ...;
builder.RegisterAssemblyTypes(assembly).AsClosedTypesOf(typeof(OpenGeneric<>))
.As<IAnInterface>();
var resolved = container.Resolve<IEnumerable<IAnInterface>>();
Run Code Online (Sandbox Code Playgroud)
使用 Ninject 3.0.0-rc3 你可以使用
kernel.Bind(
x => x.FromThisAssembly()
.SelectAllClasses().InheritedFrom(typeof(BaseService<>)).WhichAreGeneric()
.BindToAllInterfaces());
Run Code Online (Sandbox Code Playgroud)
根据您的要求,您可以删除该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
Run Code Online (Sandbox Code Playgroud)
IBar<T1, T2>是唯一有效的接口Bar<T1, T2>。但对于 Foo 来说,两者IBar<int, int>, IFoo都是有效的。