Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity, Using Statement and PerRequestLifetimeManager

I'm using Unity in my project. But I'm unsure whether I should be using the using statement or not as I'm using the PerRequestLifetimeManager.

Simple example:

Injection:

container.RegisterType<IDataContext, MyContext>(new PerRequestLifetimeManager());

Usage:

class MyClass
{
     private readonly IDataContext _context;

     public MyClass(IDataContext context)
     {
           _context = context;
     }

     public string MyMethod()
     {
          // 1. Is this needed?
          using (var u = _context)
          {
               var customers = u.Set<Customer>().OrderBy(o => o.Name);
               // ........
          }

          // 2. OR can I just do this
          var customers = _context.Set<Customer>().OrderBy(o => o.Name);

As I'm using PerRequestLifetimeManager() in my injection, does this negate the requirement of the using statement as the context will be disposed after every http request anyway?

like image 693
mnsr Avatar asked Jun 25 '26 10:06

mnsr


1 Answers

If you would use using then you would immediately dispose DbContext and if you try to access it again it will result in exception, so 1 approach is generally bad idea. 2 would work but what if there would occur problem in DbContext, for instance new data that you would like to persist will be not compliant to db design (for instance indexes). In such case you will be unable to recreate DbContext. My advice would be to register and then resolve factory method for DbContexts:

class MyClass
{
     private readonly Func<IDataContext> _contextFactory;

     public MyClass(Func<IDataContext> contextFactory)
     {
           _contextFactory = contextFactory;
     }

     public string MyMethod()
     {
           // 1. Is this needed?
           using (var u = _contextFactory())
           { 
               var customers = u.Set<Customer>().OrderBy(o => o.Name);
               // ........
           }
     }
like image 184
mr100 Avatar answered Jun 26 '26 22:06

mr100



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!