Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7405231
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T05:22:21+00:00 2026-05-29T05:22:21+00:00

I have read as many of the posts on Stackoverflow as I can find

  • 0

I have read as many of the posts on Stackoverflow as I can find with regards the use of a Unit of Work pattern within
an ASP.Net MVC 3 application which includes a Business Layer. However, I still have a couple of questions with
regards this topic and would greatly appreciate any feedback people can give me.

I am developing an ASP.Net MVC 3 Web application which uses EF 4.1. I will be using both the Repository and
Unit of Work Patterns with this project similar to how they are used in this great tutorial

The difference in my project is that I need to also include a Business Layer (separate project in my solution) in order to
carry out the various business rules for the application. The tutorial mentioned above does not have a Business layer, and
therefore creates an instance of the Unit of Work class from the controller

public class CourseController : Controller
{
    private UnitOfWork unitOfWork = new UnitOfWork();

However, my question is, where should I create the instance of the Unit of Work class if I have a Business Layer?

I personally think it should be created in my controller and then injected into the Business Layer like so:

public class PeopleController : Controller
{
    private readonly IUnitOfWork _UoW;
    private IPersonService _personService;

    public PeopleController()
    {
        _UoW = new UnitOfWork();
        _personService = new PersonService(_UoW);
    }

    public PeopleController(IUnitOfWork UoW, IPersonService personService)
    {
        _UoW = UoW;
        _personService = personService;

    }

    public ActionResult Edit(int id)
    {
        Person person = _personService.Edit(id);
        return View(person);
    }

public class UnitOfWork : IUnitOfWork, IDisposable
{
    private BlogEntities _context = new BlogEntities();
    private PersonRepository personRepository = null;

    public IPersonRepository PersonRepository
    {
        get
        {

            if (this.personRepository == null)
            {
                this.personRepository = new PersonRepository(_context);
            }
            return personRepository;
        }
    }

    public void Save()
    {
        _context.SaveChanges();
    }


public class PersonService : IPersonService
{
    private readonly IUnitOfWork _UoW;

    public PersonService(IUnitOfWork UoW)
    {
        _UoW = UoW;
    }

    public Person Edit(int id)
    {
         Person person = _UoW.PersonRepository.GetPersonByID(id);
         return person;
    }

public class PersonRepository : IPersonRepository
{
    private readonly BlogEntities _context;

    public PersonRepository(BlogEntities context)
    {
        _context = context;
    }

    public Person GetPersonByID(int ID)
    {
        return _context.People.Where(p => p.ID == ID).Single();
    }

I have read others saying that the Unit of Work instantiation should not be in the Controller, but created in the Service Layer
instead. The reason why I am not so sure about this approach is because my Controller may have to use several different
Service Layers in one business transaction, and if the Unit of Work instance was created inside each Service, it would result in several
Unit of Work instances being created, which defeats the purpose, ie, one Unit of Work per business transaction.

Maybe what I have explained above is wrong, but if so, I would greatly appreciate if someone could put me right.

Thanks again for your help.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T05:22:22+00:00Added an answer on May 29, 2026 at 5:22 am

    I think you have a couple of changes to make:.

    1. Allow your DI container to inject a UnitOfWork instance into your Service classes in their constructors, and leave it out of your Controller altogether.

    2. If your DI container supports it (Ninject does, for example), configure your UnitOfWork to be managed on a per-request basis; this way your services will be handed a distinct UnitOfWork for each request, and you’re all done. Or…

    3. If your DI container does not support per-request lifetimes, configure it to manage the UnitOfWork as a singleton, so every Service class gets the same instance. Then update your UnitOfWork to store its Entities object in a data store which stores objects on a per-request basis, for example in HttpContext.Current.Items, as described here.

    Edit 1

    Regarding where the UnitOfWork should be injected; I’d say the Service layer is the correct place. If you imagine your system as a series of layers where the outer layers deal with user interactions and the lower layers deal with data storage, each layer should become less concerned with users and more concerned with data storage. UnitOfWork is a concept from one of the ‘lower-level’ layers and Controller is from a higher-level layer; your Service layer fits between them. It therefore makes sense to put the UnitOfWork into the Service class rather than the Controller.

    Edit 2

    To elaborate on the UnitOfWork creation and it’s relationship to HttpContext.Current.Items:

    Your UnitOfWork would no longer hold a reference to an Entities object, that would be done through the HttpContext object, injected into the UnitOfWork behind an interface like this:

    public interface IPerRequestDataStore : IDisposable
    {
        bool Contains(string key);
    
        void Store<T>(string key, T value);
    
        T Get<T>(string key);
    }
    

    The HttpContext object would then implement IPerRequestDataStore like this:

    public class StaticHttpContextPerRequestDataStore : IPerRequestDataStore
    {
        public bool Contains(string key)
        {
            return HttpContext.Current.Items.Contains(key);
        }
    
        public void Store<T>(string key, T value)
        {
            HttpContext.Current.Items[key] = value;
        }
    
        public T Get<T>(string key)
        {
            if (!this.Contains(key))
            {
                return default(T);
            }
    
            return (T)HttpContext.Current.Items[key];
        }
    
        public void Dispose()
        {
            var disposables = HttpContext.Current.Items.Values.OfType<IDisposable>();
    
            foreach (var disposable in disposables)
            {
                disposable.Dispose();
            }
        }
    }
    

    As an aside, I’ve called it StaticHttpContextPerRequestDataStore as it uses the static HttpContext.Current property; that’s not ideal for unit testing (another topic altogether), but at least the name indicates the nature of its dependency.

    Your UnitOfWork then passes the IPerRequestDataStore it’s given to each of its Repository objects so they can access the Entities; this means that no matter how many UnitOfWork instances you create, you’ll use the same Entities object throughout a request because it’s stored and retrieved in the IPerRequestDataStore.

    You’d have an abstract base Repository which would use its IPerRequestDataStore to lazy-load its Entities object like this:

    public abstract class RepositoryBase : IDisposable
    {
        private readonly IPerRequestDataStore _dataStore;
    
        private PersonRepository personRepository;
    
        protected RepositoryBase(IPerRequestDataStore dataStore)
        {
            this._dataStore = dataStore;
        }
    
        protected BlogEntities Context
        {
            get
            {
                const string contextKey = "context";
    
                if (!this._dataStore.Contains(contextKey))
                {
                    this._dataStore.Store(contextKey, new BlogEntities());
                }
    
                return this._dataStore.Get<BlogEntities>(contextKey);
            }
        }
    
        public void Dispose()
        {
            this._dataStore.Dispose();
        }
    }
    

    Your PeopleRepository (for example) would look like this:

    public class PeopleRepository : RepositoryBase, IPersonRepository
    {
        public PeopleRepository(IPerRequestDataStore dataStore) 
            : base(dataStore)
        {
        }
    
        public Person FindById(int personId)
        {
            return this.Context.Persons.FirstOrDefault(p => p.PersonId == personId);
        }
    }
    

    And finally, here’s the creation of your PeopleController:

    IPerRequestDataStore dataStore = new StaticHttpContextDataStore();
    UnitOfWork unitOfWork = new UnitOfWork(dataStore);
    PeopleService service = new PeopleService(unitOfWork);
    PeopleController controller = new PeopleController(service);
    

    One of the central concepts here is that objects have their dependencies injected into them via their constructors; this is generally accepted as good practice, and more easily allows you to compose objects from other objects.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have read many posts about setting up unit testing in Zend Framework and
I have read many posts on this topic; among them and most recently .NET
Alright...I've given the site a fair search and have read over many posts about
I have read so many times, here and everywhere on the net, that mutexes
Ignoring unsafe code, .NET cannot have memory leaks. I've read this endlessly from many
OK I have read many posts regarding Dual Licensing using MIT and GPL licenses.
I have read many posts and blogs about rewriting and I know there is
I have read many posts about this now but I do not still understand
I have read many posts regarding detection of popup blocker by javascript code but
I have read many posts on Session-scoped data in MVC, but I am still

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.