开发者

Should We Instantiate Data Context & Repository In Controller?

I have an ObjectContext and a Repository that gets passed the ObjectContext. I the开发者_JS百科n 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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜