使用Ninject 3.0.0进行基于约定的依赖注入

时间:2012-03-22 14:59:36

标签: dependency-injection ninject ninject-extensions

我的解决方案中有两个项目......一个域项目和一个MVC3 Web项目(例如MyApp.Domain和MyApp.Web)。以前,使用 Ninject.Extensions.Conventions 版本时。 2,我能够在NinjectMVC3.cs文件中使用以下语句,并且在我的解决方案(web和域)中所需的依赖项被正确注入(例如,IFoo自动绑定到Foo)。

kernel.Scan(x =>
{
  x.FromAssembliesMatching("*");
  x.BindWith<DefaultBindingGenerator>();
});

我刚刚升级到Ninject 3.0.0(预发行版)和Ninject.Extensions.Conventions 3.0.0(另一个预发行版),但基于约定的绑定的语法已经改变。我已经发现我可以在新版本中使用以下语句,但它只会自动绑定MyApp.Web中基于约定的接口而不是MyApp.Domain。以前的版本绑定了整个应用程序的接口。

kernel.Bind(x => x
    .FromThisAssembly()
    .SelectAllClasses()
    .BindToAllInterfaces());

我是如何使用新的Ninject版本配置基于约定的绑定的?我假设它与指定程序集有关,但我尝试使用FromAssembliesMatching("*"),然后它就失败了。

- 编辑以在RegisterServices方法中显示我现有的代码: -

private static void RegisterServices(IKernel kernel)
{
  // This code used to work with v.2 of Ninject.Extensions.Conventions
  // kernel.Scan(x =>
  // {
  //   x.FromAssembliesMatching("*");
  //   x.BindWith<DefaultBindingGenerator>();
  // });

  // This is the new v3 code that automatically injects dependencies but only for interfaces in MyApp.Web, not MyApp.Domain
  kernel.Bind(x => x.FromThisAssembly().SelectAllClasses().BindToAllInterfaces()); 

  // I tried this code, but it throws "Error activating IDependencyResolver" at "bootstrapper.Initialize(CreateKernel)"
  // kernel.Bind(x => x.FromAssembliesInPath(AppDomain.CurrentDomain.RelativeSearchPath).SelectAllClasses().BindToAllInterfaces());

  // These are dependencies in MyApp.Web that ARE being bound properly by the current configuration
  // kernel.Bind<IMemberQueries>().To<MemberQueries>();
  // kernel.Bind<IGrantApplicationQueries>().To<GrantApplicationQueries>();
  // kernel.Bind<IMailController>().To<MailController>();

  // These are dependencies in MyApp.Domain that ARE NOT being bound properly by the current configuration, so I have to declare them manually 
  // They used to be injected automatically with version 2 of the conventions extention
  kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
  kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
  kernel.Bind<IMemberServices>().To<MemberServices>();
  kernel.Bind<IGrantApplicationServices>().To<GrantApplicationServices>();

  // These are dependencies that SHOULD NOT be bound by convention as they require a different scope or have unique naming
  kernel.Bind(typeof(EfDbContext)).ToSelf().InRequestScope();
  kernel.Bind<IConfigurationProvider>().To<WebConfigConfigurationProvider>().InSingletonScope();
  kernel.Bind<IAuthorizationProvider>().To<MyAppAuthorizationProvider>();
  kernel.Bind<IPrincipal>().ToMethod(ctx => HttpContext.Current.User).InRequestScope();
  kernel.Bind<IGrantApplicationDocumentServices>().To<MySpecialNameGrantAplicationDocumentServices>().InRequestScope();
}

1 个答案:

答案 0 :(得分:17)

等效于:

kernel.Bind(x => x
    .FromAssembliesMatching("*")
    .SelectAllClasses()
    .BindDefaultInterface());