tags:

views:

50

answers:

1

I have an ObjectContext and a Repository that gets passed the ObjectContext. I then use the repository to make calls. I want to use dependency injection to not always have to instantiate the ObjectContext and Repository. What "object" would I group the context / repository into?

using (MOSContext db = new MOSContext())
{
    IUserRepository users = new UserRepository(db);

    // Do stuff with users.
}

Is this bad to do the above? Ideally, I'd like to be able to create "some object" that acts like the ObjectContext, but has accessors to all repository interfaces:

using (IDAL dal = IoC.Resolve<IDal>())
{
    dal.Users.GetById(myId);
    dal.Profiles.Add(new Profile());
}

Then using DI, I can register the context and all implementations for each repository interface.

A: 

Yes, it's bad to new up OCs in the controller. Yes, it's better to use DI to return an instance of an interface not strictly tied to the EF.

You should have one instance of the OC per request, not per method. Most DI containers have a request-scoped lifetime feature out of the box.

Craig Stuntz
But should the OC have properties to access the repositories? If not, what class should they sit in? Or should I do what I have in the first block of code, only with DI?Also, I'm trying to roll my on IoC to learn how it's done. Would having a `using` statement be sufficient?
TheCloudlessSky
The short answer is this: Go buy Mark Seeman's *Dependency Injection in .NET* (Manning Books). It *thoroughly* answers your questions. It also happens to use MVC and the EF as its sample app.
Craig Stuntz
Would there be any free resources you can direct me to? I'm a student and don't really have a big budget.
TheCloudlessSky
??? The book is under $30. What does your school cost?
Craig Stuntz
Justifying pending $30 on a book that I'll read probably only once, versus having it freely available on the internet is important to some people, including me.
TheCloudlessSky
@TheCloudlessSky if you want free, checkout the source for a project called "Suteki Shop", he uses the generic repository pattern and Castle Windsor IoC to wire it up. It's free, but you have to work it out from the source yourself. HTH
amarsuperstar
@amarsuperstar - Yeah that's exactly what I was looking for. An implementation inside a "real" project. Thanks for that!
TheCloudlessSky