Question

I have an application that uses a generic repository pattern for data access. As the application requires the use of several different databases I've implemented a repository factory using the Ninject Factory Extension. This allows me to create repositories for the various databases on demand. I simply pass the DBContext to the factory as follows:

    private readonly IRepository database1;
    private readonly IRepository database2;

    public MembershipService(IRepositoryFactory repositoryFactory)
    {
        this.database1 = repositoryFactory.CreateRepository(new Context("Database1"));
        this.database2 = repositoryFactory.CreateRepository(new Context("Database2"));
    }

What's annoying with this code is the string required to create a Context. The strings "Database1" and "Database2" in the example above. When the above code is used many, many times throughout the project it's far too easy for a simple typo to cause major problems.

How can I remedy this situation? Should I create a context factory? That would still require the database name. Could I somehow use Enums? I've been tossing around a bunch of ideas but nothing seems to fit quite right

Was it helpful?

Solution

Put a constructor that accepts DbContext on the deriving class of your IRepositoryFactory

class RepositoryFactory : IRepositoryFactory
{
    DbContext _dbc;
    public RepositoryFactory(DbContext db)
    {
       _dbc = db;
    }

    public IRepository CreateRepository()
    {
        return new Repository(_dbc);
    }
}

Then you bind that DbContext on your Ninject injection bindings, put this along with your other bindings:

ninjectKernel.Bind<DbContext>().To<EfDbContext>().InRequestScope();

I'm just taking a guess here, this is how your injection bindings for RepositoryFactory looks like:

ninjectKernel.Bind<IRepositoryFactory<Person>>().To<RepositoryFactory<Person>>();

If you made those two bindings next to each other (order is not important), Ninject shall be able to do an injection of value to the DbContext parameter of your RepositoryFactory's constructor.


An example

Look at line 60 to 76 here: http://code.google.com/p/flexigrid-crud-example/source/browse/trunk/FlexigridCrudDemo/FlexigridCrudDemo/NinjectDependencyResolver.cs

See the repository pattern for EF here, line 22: http://code.google.com/p/to-the-efnh-x/source/browse/trunk/ToTheEfnhX/Ienablemuch.ToTheEfnhX.EntityFramework/EfRepository.cs

See the repository pattern for NHibernate here, line 24: http://code.google.com/p/to-the-efnh-x/source/browse/trunk/ToTheEfnhX/Ienablemuch.ToTheEfnhX.NHibernate/NhRepository.cs

And how I abstracted those two dissimilar ORMs with repository pattern, the depency injection for connections(DbContext for Entity Framework, Session for NHibernate) is facilitated by Ninject:

int target = 1; // memory, nhibernate, entity framework

switch (target)
{
    case 0:
        ninjectKernel.Bind<IRepository<Person>>().ToMethod(x =>
        {
            var person = new MemoryRepository<Person>();
            person.Save(new Person { Username = "Hello", Firstname = "Yo", FavoriteNumber = 9 }, null);
            person.Save(new Person { Username= "See", Firstname = "Nice" }, null);

            return person;
        }
        ).InSingletonScope();


        break;

    case 1:
        ninjectKernel.Bind<ISession>().ToMethod(x => ModelsMapper.GetSessionFactory().OpenSession()).InRequestScope();
        ninjectKernel.Bind<Ienablemuch.ToTheEfnhX.IRepository<Person>>().To<Ienablemuch.ToTheEfnhX.NHibernate.NhRepository<Person>>();
        ninjectKernel.Bind<Ienablemuch.ToTheEfnhX.IRepository<Country>>().To<Ienablemuch.ToTheEfnhX.NHibernate.NhRepository<Country>>();


        break;



    case 2:

        ninjectKernel.Bind<DbContext>().To<EfDbContext>().InRequestScope();
        ninjectKernel.Bind<Ienablemuch.ToTheEfnhX.IRepository<Person>>().To<Ienablemuch.ToTheEfnhX.EntityFramework.EfRepository<Person>>();
        ninjectKernel.Bind<Ienablemuch.ToTheEfnhX.IRepository<Country>>().To<Ienablemuch.ToTheEfnhX.EntityFramework.EfRepository<Country>>();

        break;

    default:
        break;
}

OTHER TIPS

I had the same problem with my generic repository pattern, heres how I solved it:

http://blog.staticvoid.co.nz/2012/01/multiple-repository-data-contexts-with.html

This allows me to declare repositories of specific types based on namespace to come from different databases.

In terms of usage, you could then go

public MembershipService(IRepository<User> userRepository, IRepository<AppRole> roleRepository)

where User and AppRole come from seperate DBcontexts

If you have a different DbContext type for each database, you can simplify the process by creating two bindings:

kernel.Bind<DatabaseDbContext1>().ToSelf().InRequestScope();

kernel.Bind<DatabaseDbContext2>().ToSelf().InRequestScope();

In the Repository constructor include both types:

public Repository(DbContext1, DbContext2)

You do not need to place the connection string name in the DBContext constructors. Just name each connection string the same as each DbContext name. EntityFramework will work out the rest.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top