开发者

Resolving with rules in Unity?

开发者 https://www.devze.com 2023-03-26 20:48 出处:网络
I have interface IRepository that maps to the class GenericRepository in unity. IOC.Container.RegisterType<IRepository, GenericRepository>();

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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号