ASP.NET MVC Software Design Pattern: DI,Repository,Service Layer

前端 未结 1 1824
长发绾君心
长发绾君心 2021-02-01 11:20

EDIT

Should i put service layer and repository layer into one project, so the web project is able to reference to DbContext objects ? Now my web(control

相关标签:
1条回答
  • 2021-02-01 11:50

    I believe you really should add a TEntity GetById(int id) to your IRepository<TEntity> generic interface.

    Why? Because if you don't, and if you want to fetch a single record on your business layer, you only have two options (on the repository, data-access layer):

    1. Return a complete, "unlazy" collection, meaning that you'll return, say, 100,000 records in order to use a single one.
    2. Return a lazy collection like IQueryable<TEntity>, which, yes, will allow you to get a single record from the database, but may cause a lot of nasty side-effects.

    The first option is clearly wrong. The second is controversial, but (unless your project has you as a single developer, and you really really really know what you're doing) it is potentially leaky and unsafe. So, if you do need a single record (and sometimes you'll surely do), expose a method that does exactly that.

    Having said that, you should also not expose IQueryable<TEntity> All { get; }, for exactly the same reasons above. Use IEnumerable<TEntity> All { get; } instead, and make your concrete generic repository class return a real collection, by calling context.Set<TEntity>().ToList() for instance.

    Edit

    Regarding IDisposable:

    There are only two (related) reasons for implementing the IDisposable interface that I can think of:

    1. Disposing unmanaged resources
    2. A cool way of implementing the RAII pattern.

    In your case, you probably should use it on your repository implementation. Please take a look at this SO question for further information.

    0 讨论(0)
提交回复
热议问题