How to use Simple injector, Repository and Context - code first

前端 未结 1 706
广开言路
广开言路 2020-12-31 11:33

I\'m trying to use Simple Injector to create my repository and use it in the Business logic layer ( also i want to use PerWebRequest method ) .

In the DAL layer i ha

相关标签:
1条回答
  • 2020-12-31 11:46

    Since you will probably have many IReposotory<T> implementations (for Product, Customer, Employee, etc), it's better make a single open generic registration for IRepository<T> like this:

    container.Register(typeof(IRepository<>), typeof(EFRepository<>), Lifestyle.Scoped);
    

    Where the scoped lifestyle is defined as:

    container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
    

    This registration ensures that Simple Injector will return a EFRepository<Product>, every time a IRepository<Product> is requested, an EFRepository<Customer> for IRepository<Customer>, and so on, and so on.

    Since you want the same DbContext instance to be used over all repositories within the same request, you should also register the DbContext with the scoped Lifestyle:

    container.Register<DbContext, PASContext>(Lifestyle.Scoped);
    

    In the BLL i have a class ProductBLL and i want to get all products from the database and pass it to, lets say HomeController

    In that scenario, this ProductBLL seems like a useless abstraction to me. If all it does is passing data through, you can as easily let your HomeController depend on IRepository<Product> directly.

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