Reputation: 82507
I have interface IRepository that maps to the class GenericRepository in unity.
IOC.Container.RegisterType<IRepository, GenericRepository>();
(GenericRepository takes a ObjectContext (Entity Framework context) to perform its data actions)
The problem is that I need several different instances of GenericRepository. (I have several Entity Framework models in my solution)
In each part of the business layer logic I need to resolve IRepository and get a GenericRepository that was initialized for the Model that corresponds to that part of the business layer logic.
I need some way to setup with options... I don't know if this is a problem unique to me or if others have had this too.
Is there a way to tell Unity how to do this?
NOTE: I would prefer not to pass an instance of the ObjectContext in as a parameter to the Resolve method. If I do that then I defeat the purpose for the Repository pattern (abstracting the data layer so I can unit test easily).
Upvotes: 2
Views: 257
Reputation: 82507
I think this will work:
IOC.Container.RegisterType<IRepository, GenericRepository>("ModelOne",
new InjectionConstructor(new ModelOneEntities());
IOC.Container.RegisterType<IRepository, GenericRepository>("ModelTwo",
new InjectionConstructor(new ModelTwoEntities());
.....
IRepository modelOneRepository = IOC.Container.Resolve<IRepository>("ModelOne");
Basically you name each registration and provide the constructor parameters that make it different. You then use that name when you resolve (though I suggest const
values instead of magic strings).
Upvotes: 1
Reputation: 50018
Could you have the specific repository implementations define there own interface? So something like this:
IOC.Container.RegisterType<IModel1Repository, GenericRepository>();
IOC.Container.RegisterType<IModel2Repository, GenericRepository>();
interface IModel1Repository : IRepository
interface IModel2Repository : IRepository
class GenericRepository : IModel1Repository
{
// Model1 specific ObjectContext
}
class GenericRepository : IModel2Repository
{
// Model2 specific ObjectContext
}
Then you could lookup based on the model specific repository.
Upvotes: 0