Ninject 多类型构造函数
Ninject Multiple Type Constructor
我今天开始使用 Ninject 因为 Structuremap 让我很失望。
当我开始注册具有相同接口的相同类型但我已经命名它们(如下所示)时,我遇到了一个问题。
kernel.Bind<IDataContextAsync>().To<DbGeoContext>().InRequestScope().Named("DbGeoContext");
kernel.Bind<IDataContextAsync>().To<DbEspContext>().InRequestScope().Named("DbEspContext");
IParameter geoUnitOfWorkDbContext = new ConstructorArgument("dataContext", kernel.Get<IDataContextAsync>("DbGeoContext"));
IParameter espUnitOfWorkDbContext = new ConstructorArgument("dataContext", kernel.Get<IDataContextAsync>("DbEspContext"));
kernel.Bind<IUnitOfWorkAsync>().To<UnitOfWork>().Named("UnitOfWorkGeoContext").WithConstructorArgument(geoUnitOfWorkDbContext);
kernel.Bind<IUnitOfWorkAsync>().To<UnitOfWork>().Named("UnitOfWorkEspContext").WithConstructorArgument(espUnitOfWorkDbContext);
**Fails here with: Error activating IDataContextAsync
有多个匹配绑定可用。**
var t1 = kernel.Get("UnitOfWorkGeoContext");
var t2 = kernel.Get("UnitOfWorkEspContext");
有人可以帮我弄清楚这是怎么回事以及如何解决吗?
我知道在运行时 Ninject 无法确定要注入哪个实例,但我认为这就是 'Named' 实例的用途?
谢谢
当使用 Ninject 定位同一接口的多个实现时,您需要像之前那样使用 .Named
调用。但是您还需要在构造函数上添加 Named
属性,以便 Ninject 知道要解析哪个实现。
如图所示:
示例
class SomeClassThatConsumesOneOfYourImplementations
{
public SomeClassThatConsumesOneOfYourImplementations(
[Named("DbGeoContext")] IDataContextAsync context)
{
// Constructor logic...
}
}
我今天开始使用 Ninject 因为 Structuremap 让我很失望。
当我开始注册具有相同接口的相同类型但我已经命名它们(如下所示)时,我遇到了一个问题。
kernel.Bind<IDataContextAsync>().To<DbGeoContext>().InRequestScope().Named("DbGeoContext");
kernel.Bind<IDataContextAsync>().To<DbEspContext>().InRequestScope().Named("DbEspContext");
IParameter geoUnitOfWorkDbContext = new ConstructorArgument("dataContext", kernel.Get<IDataContextAsync>("DbGeoContext"));
IParameter espUnitOfWorkDbContext = new ConstructorArgument("dataContext", kernel.Get<IDataContextAsync>("DbEspContext"));
kernel.Bind<IUnitOfWorkAsync>().To<UnitOfWork>().Named("UnitOfWorkGeoContext").WithConstructorArgument(geoUnitOfWorkDbContext);
kernel.Bind<IUnitOfWorkAsync>().To<UnitOfWork>().Named("UnitOfWorkEspContext").WithConstructorArgument(espUnitOfWorkDbContext);
**Fails here with: Error activating IDataContextAsync
有多个匹配绑定可用。**
var t1 = kernel.Get("UnitOfWorkGeoContext"); var t2 = kernel.Get("UnitOfWorkEspContext");
有人可以帮我弄清楚这是怎么回事以及如何解决吗?
我知道在运行时 Ninject 无法确定要注入哪个实例,但我认为这就是 'Named' 实例的用途?
谢谢
当使用 Ninject 定位同一接口的多个实现时,您需要像之前那样使用 .Named
调用。但是您还需要在构造函数上添加 Named
属性,以便 Ninject 知道要解析哪个实现。
如图所示:
示例
class SomeClassThatConsumesOneOfYourImplementations
{
public SomeClassThatConsumesOneOfYourImplementations(
[Named("DbGeoContext")] IDataContextAsync context)
{
// Constructor logic...
}
}