0

I have 2 Dbcontext class AdminDbContext , and AppDbContext for my web api project,both them implements IDbcontext.

My problem is Ninject is not able to resolve dependency so i get parameterless constructor error

i do not have any specific condition so contextual binding seems tough please help with this

1
  • you can always choose to bind and inject AdminDbContext and AppDbContext directly... Commented Feb 26, 2016 at 19:54

1 Answer 1

1

If I understand the question correctly you can't inject IDbContext into your class as you sometimes need AdminDbContext and sometimes AppDbContext within the same class, so you can't write the Ninject binding.

In this case you can write an IDbContextFactory interface and inject that.

public interface IDbContextFactory
{
    IDbContext CreateAdminContext();
    IDbContext CreateAppContext();
}

public class DbContextFactory : IDbContextFactory
{
    //implementation of above interface methods to return the relevant context.
}

Then your class can inject that instead of the context

public class YourClass
{
    private readonly IDbContextFactory _factory;

    public YourClass(IDbContextFactory factory)
    {
        _factory = factory;
    }

    public YourAdminMethod()
    {
        using (var context = _factory.CreateAdminContext())
        {
            //do stuff
        }
    }

    public YourAppMethod()
    {
        using (var context = _factory.CreateAppContext())
        {
            //do stuff
        }
    }
}

and then you just need one binding in your Ninject bindings for IDbContextFactory, which can be singleton.

kernel.Bind<IDbContextFactory>().To<DbContextFactory>().InSingletonScope();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.