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(){}
}
4
  • you can check it - does your DbFactory dispose at the end of request? Commented Oct 20, 2015 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. Commented Oct 20, 2015 at 13:41
  • this factory is created for every child container. Do you use child containers? Commented Oct 20, 2015 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. Commented Oct 20, 2015 at 13:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.