Ninject Providers -> Get another dependency inside

2019-07-03 00:45发布

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?

2条回答
我命由我不由天
2楼-- · 2019-07-03 01:35

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);
    }
}
查看更多
看我几分像从前
3楼-- · 2019-07-03 01:45

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);
    }
}
查看更多
登录 后发表回答