我的解决方案中有两个项目... 一个是域项目,另一个是MVC3 Web项目(例如MyApp.Domain和MyApp.Web)。以前,当使用Ninject.Extensions.Conventions ver.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();
}
x.FromAssembliesMatching("*")
可以工作并绑定 MyApp.Web 和 MyApp.Domain 中的所有接口。然而,在新的 3.0.0 版本中,这个语法不起作用。我找到的最接近的是x.FromThisAssembly()
,但它只会绑定 MyApp.Web 中的接口(因为注入发生在那里)。它不会自动绑定 MyApp.Domain 中的接口。 - bigmac.FromAssembliesInPath(AppDomain.CurrentDomain.RelativeSearchPath)
,它将产生<绝对路径到你的wwwroot\app\bin>
。 - Ruben Bartelink