2

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).

SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
Vaccano
  • 78,325
  • 149
  • 468
  • 850

2 Answers2

1

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).

Vaccano
  • 78,325
  • 149
  • 468
  • 850
0

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.

SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
  • Yes, I could do that. But I will potentially have a lot of models and that is a fair amount of extra work. I will keep this solution as a backup plan. --- I have been looking into this problem more and I saw that Unity allows for a name when RegisterType is called. I am wondering if I could use when I call Resolve. The only problem is that I need to pass in the constructor I want used for each named RegisterType call (haven't figured out if that is even possible.) – Vaccano Aug 09 '11 at 18:32