1

I am implementing dependency injection using Unity and the Unity.Webforms bootstrapper. I have a DbFactory in my webforms application which initializes my DbContext, and I am wanting to create one instance of this factory per web request, so that my various services will update under the same unit of work.

My question is, does the Unity.Webforms bootstrapper take care of this for me? I believe the answer in this post is suggesting doing the following in order accomplish a single context per request.

container.RegisterType<IDbFactory,DbFactory>(new HierarchicalLifetimeManager()); 

Is this correct, and is it all I need to do? I'm worried that it is creating a single context per request, but that it is an application wide context (all users sharing the same context).

This probably isn't necessary, but just in case, here is the implementation code for my DbFactory.

public class DbFactory : Disposable, IDbFactory
{
   MyDbContext dbContext;

   public MyDbContext Init()
   {
      return dbContext ?? (dbContext = new MyDbContext());
   }

   protected override void DisposeCore()
   {
       if(dbContext != null)
       {
           dbContext.Dispose();
       }
   }
}

public class Disposable : IDisposable
{

    private bool isDisposed;

    ~Disposable()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if(!isDisposed && disposing)
        {
            DisposeCore();
        }
        isDisposed = true;
    }

    protected virtual void DisposeCore(){}
}
Community
  • 1
  • 1
user2023116
  • 423
  • 2
  • 6
  • 16
  • you can check it - does your DbFactory dispose at the end of request? – Backs Oct 20 '15 at 12:32
  • @Backs It does dispose, but is that factory being created for a single thread across the application? I'm not sure how to test that. – user2023116 Oct 20 '15 at 13:41
  • this factory is created for every child container. Do you use child containers? – Backs Oct 20 '15 at 13:48
  • I'm not explicitly creating any, as far as I know. I am using that line of code I mentioned which uses the hierarchical life time manager, and I _think_ the bootstrapper takes care of the rest, but that is what I am unsure about. – user2023116 Oct 20 '15 at 13:59

0 Answers0