Acaz Souza
Acaz Souza

Reputation: 8631

What's best way to inject context in my base repository?

I have a BaseRepository that depends a DbContext to perform the database operations:

public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : Entity
{
   ...
}

I don't want to insert this dependency using Constructor Dependency Injection, because if I use I'll need to pass these dependency in constructors of derived repositories. I don't want to use Property/Setter Dependency Injection too because Property/Setter Dependency Injection indicates dependency is optional, which is not the case.

My DbContext inherit from IDbContext interface, where is my UnitOfWork Pattern:

public class DbContext : System.Data.Entity.DbContext, IDbContext
{
   ...
}

And I've set my IDbContext using Ninject:

public override void Load()
{
   Bind<IDbContext>().To<DbContext>().InRequestScope();
}

My question is how I inject DbContext in Base Repository, and I need a single instance of DbContext in a requestScope. (Using a Factory?)

Upvotes: 0

Views: 2050

Answers (2)

Acaz Souza
Acaz Souza

Reputation: 8631

I found the solution using the Service Locator of Ninject and took back the instance of DbContext:

public class ExampleClass()
{
    protected DbContext DbContext
    {
        get
        {
                                                                        //Here I do the trick I wanted
            return DependencyResolverFactory.Instance.Get<IDbContext>() as DbContext;
        }
    }

    ...
}

And my Dependency Resolver class:

public static class DependencyResolver
{
    private static IKernel _kernel;

    static DependencyResolver()
    {
        _kernel = new StandardKernel();
        _kernel.Load(Assembly.GetExecutingAssembly());
    }

    public static IKernel GetCurrentKernel()
    {
        return _kernel;
    }

    public static void RegisterKernel(IKernel kernel)
    {
        _kernel = kernel;
    }

    public static T Get<T>()
    {
        return _kernel.Get<T>();
    }
}

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160892

Generally since your repository needs a DBContext you should use constructor injection - the context is not optional.

If your repository instances are created using Ninject it does not matter that you need to pass in a DBContext - the dependency will be resolved for you.

If you want to "manually" create repository instances you can use a factory that already has the DBContext dependency so consumers don't have to worry about it.

Upvotes: 3

Related Questions