问题
I'm wondering what the best practices is here. I need to construct a DbContext for my multi tenanted application, so I have made a Dependency provider like this:
public class TenantContextFactoryProvider : Provider<DbContext>
{
protected override DbContext CreateInstance(IContext context)
{
var tenant = // How to get the tenant through ninject??
return new DbContext(tenant.ConnectionString);
}
}
I need ninject to resolve the tenant dependency, but I'm not sure how to do this?
回答1:
While service locator certainly works, constructor injection is another choice.
public class TenantContextFactoryProvider : Provider<DbContext>
{
ITenant tenant;
public TenantContextFactoryProvider(ITenant tenant)
{
this.tenant = tenant;
}
protected override DbContext CreateInstance(IContext context)
{
return new DbContext(tenant.ConnectionString);
}
}
回答2:
This is a bit embarassing, but I guess if it can happen to me, it can happen to someone else as well.
I forgot to include using Ninject
, which is why the extension method context.Kernel.Get
wasn't showing up, in IntelliSense.
So my code ended up looking like this:
using Ninject;
public class TenantContextFactoryProvider : Provider<DbContext>
{
protected override DbContext CreateInstance(IContext context)
{
var tenant = context.Kernel.Get<ITenant>();
return new DbContext(tenant.ConnectionString);
}
}
来源:https://stackoverflow.com/questions/30001121/ninject-providers-get-another-dependency-inside-the-provider