找到你要的答案

Q:Ninject Providers -> Get another dependency inside the provider

Q:Ninject供应商->再依赖内部供应商

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?

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);
    }
}

我需要解决租客Ninject依赖,但我不知道该怎么办?

answer1: 回答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);
    }
}

虽然服务定位器当然有效,构造函数注入是另一种选择。

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);
    }
}
answer2: 回答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);
    }
}

这是一个有点尴尬,但我想如果它可以发生在我的身上,它可以发生在别人身上一样。

我忘了包括使用Ninject,这就是为什么扩展方法context.kernel.get不露面,在智能感知。

所以我的代码看起来像这样:

using Ninject;
public class TenantContextFactoryProvider : Provider<DbContext>
{
    protected override DbContext CreateInstance(IContext context)
    {
        var tenant = context.Kernel.Get<ITenant>();
        return new DbContext(tenant.ConnectionString);
    }
}
c#  dependency-injection  ninject