Ninject Providers -> Get another dependency inside the provider

感情迁移 提交于 2019-12-10 18:53:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!