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 6132665
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T17:07:48+00:00 2026-05-23T17:07:48+00:00

I’m creating my first N-Tier MVC application and I’ve run into a road block

  • 0

I’m creating my first N-Tier MVC application and I’ve run into a road block with how to manage multiple DbContexts with my database first approach.

I have the following layers

Presentation
Service (WCF)
Business
Data Access

I don’t want an entity framework reference in my service layer but I don’t see how to create an Interface or something to manage two contexts. I have it working with a single context warpped in a IDatabaseFactory but I can’t seem to find an approach to manage two.

Below is my UnitOfWork that is created in my Service ctor but every way I look at it I’m still tied to the SiteModelContainer, when in fact I have another context.

public class UnitOfWork : IUnitOfWork
    {
        private SiteModelContainer _context;

        private readonly IDatabaseFactory _databaseFactory;

        protected SiteModelContainer SiteContext
        {
            get { return _context ?? (_context = _databaseFactory.Get()); }
        }

        public UnitOfWork(IDatabaseFactory factory)
        {
            _databaseFactory = factory;
            _context = _databaseFactory.Get();
        }
        //More code
    }



public class DatabaseFactory : Disposable, IDatabaseFactory
{
    private SiteModelContainer _dataContext;

    public SiteModelContainer Get()
    {
        return _dataContext ?? (_dataContext = new SiteModelContainer());
    }

    protected override void DisposeCore()
    {
        if (_dataContext != null)
            _dataContext.Dispose();
    }
}
  • 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-23T17:07:49+00:00Added an answer on May 23, 2026 at 5:07 pm

    Giving your Factory and UnitOfWork a generic type parameter might be a solution:

    public class UnitOfWork<T> : IUnitOfWork<T>
        where T : DbContext, new()
    {
        private T _context;
    
        private readonly IDatabaseFactory<T> _databaseFactory;
    
        protected T Context
        {
            get { return _context ?? (_context = _databaseFactory.Get()); }
        }
    
        public UnitOfWork(IDatabaseFactory<T> factory)
        {
            _databaseFactory = factory;
            _context = _databaseFactory.Get();
        }
        //More code
    }
    
    public class DatabaseFactory<T> : Disposable, IDatabaseFactory<T>
        where T : DbContext, new()
    {
        private T _dataContext;
    
        public T Get()
        {
            return _dataContext ?? (_dataContext = new T());
        }
    
        protected override void DisposeCore()
        {
            if (_dataContext != null)
                _dataContext.Dispose();
        }
    }
    

    The IDatabaseFactory and IUnitWork interfaces would also have to be generic then.

    You could then create Unit of Works for different contexts:

    var factory1 = new DatabaseFactory<SiteModelContainer>();
    var unitOfWork1 = new UnitOfWork<SiteModelContainer>(factory1);
    
    var factory2 = new DatabaseFactory<AnotherModelContainer>();
    var unitOfWork2 = new UnitOfWork<AnotherModelContainer>(factory2);
    

    Edit:

    To get rid of the dependency on EF in your service classes you could try something like this. The service only knows these three interfaces:

    public interface IUnitOfWorkFactory
    {
        IUnitOfWork Create(string contextType);
    }
    
    public interface IUnitOfWork : IDisposable
    {
        IRepository<TEntity> CreateGenericRepository<TEntity>()
            where TEntity : class;
        void Commit();
    }
    
    public interface IRepository<T>
    {
        IQueryable<T> Find(Expression<Func<T, bool>> predicate);
        void Attach(T entity);
        void Add(T entity);
        // etc.
    }
    

    Here are special EF-specific implementations:

    public class UnitOfWorkFactory : IUnitOfWorkFactory
    {
        public IUnitOfWork Create(string contextType)
        {
            switch (contextType)
            {
                case "SiteModelContainer":
                    return new UnitOfWork<SiteModelContainer>();
                case "AnotherModelContainer":
                    return new UnitOfWork<AnotherModelContainer>();
            }
    
            throw new ArgumentException("Unknown contextType...");
        }
    }
    
    public class UnitOfWork<TContext> : IUnitOfWork
        where TContext : DbContext, new()
    {
        private TContext _dbContext;
    
        public UnitOfWork()
        {
            _dbContext = new TContext();
        }
    
        public IRepository<TEntity> CreateGenericRepository<TEntity>()
            where TEntity : class
        {
            return new Repository<TEntity>(_dbContext);
        }
    
        public void Commit()
        {
            _dbContext.SaveChanges();
        }
    
        public void Dispose()
        {
            _dbContext.Dispose();
        }
    }
    
    public class Repository<T> : IRepository<T>
        where T : class
    {
        private DbContext _dbContext;
        private DbSet<T> _dbSet;
    
        public Repository(DbContext dbContext)
        {
            _dbContext = dbContext;
            _dbSet = dbContext.Set<T>();
        }
    
        public IQueryable<T> Find(Expression<Func<T, bool>> predicate)
        {
            return _dbSet.Where(predicate);
        }
    
        public void Attach(T entity)
        {
            _dbSet.Attach(entity);
        }
    
        public void Add(T entity)
        {
            _dbSet.Add(entity);
        }
    
        // etc.
    }
    

    Your service would get a IUnitOfWorkFactory injected:

    public class MyService
    {
        private IUnitOfWorkFactory _factory;
    
        public MyService(IUnitOfWorkFactory factory)
        {
            _factory = factory;
        }
    
        public MyMethod()
        {
            using(var unitOfWork1 = _factory.Create("SiteModelContainer"))
            {
                var repo1 = unitOfWork1.
                    CreateGenericRepository<SomeEntityTypeInSiteModel>();
                // Do some work
                unitOfWork1.Commit();
            }
    
            using(var unitOfWork2 = _factory.Create("AnotherModelContainer"))
            {
                var repo2 = unitOfWork2.
                    CreateGenericRepository<SomeEntityTypeInAnotherModel>();
                // Do some work
                unitOfWork2.Commit();
            }
        }
    }
    

    When the service is created the concrete instance of the factory is injected:

    var service = new MyService(new UnitOfWorkFactory());
    

    Keep in mind that the hard work will be in the abstract repository and it’s implementation. As soon as you don’t have the EF context anymore in your service class you have to mimic a lot of methods in the repo interface supporting all necessary scenarios to manipulate the data.

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

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I have a French site that I want to parse, but am running into
I would like to run a str_replace or preg_replace which looks for certain words
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have an MVC Razor view @{ ViewBag.Title = Index; var c = (char)146;
I am currently running into a problem where an element is coming back from
I have a reasonable size flat file database of text documents mostly saved in

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.