简体   繁体   中英

How correctly implement Unit Of Work per scope and Repository in desktop server side application using Entity Framework 4?

I have an issue with implementing and registering in IoC conatainer Unit of Work pattern the problem is follow: on server side client-server application I need to access to database I'm using Entity Framework 4 ORM, and I need to create new DataContext per perquest to data base from clients application, it similar as in Web MVC applications. and I realized that I need to use Unit of Work pattern, currently I implemented like that:

    void SomeMethod()
    {
        using (var repository = _repositoryFactory.Create())
        {
            int id = 1;
            var entity = repository.GetById(id);
            // some code 

                repository.SaveOrUpdate();
        }
    }

where _repositoryFactory is registered as Single instance in IoC and returns new instance of Repository the DataContext is injected in Repository

 abstract class Repository<TEntity> : IRepository<TEntity> where TEntity : EntityBase 
{
   private readonly IDataContext _context;

    protected Repository(IDataContext context)
    {
        _context = context;
    }
  }

as IRepository as IDataContext is registered in IoC contanier as Instance per Dependancy, and what I need I want to use Unit of Work in the following way:

 void SomeMethod()
    {
        using (var unitOfWork = _unitOfWorkFactory.Create())
        {
            int id = 1;
            var entity = _repository.GetById(id);
            // some code 

                repository.Commit();
        }
    }

How correctly to implement this logic and registration in IoC or may be I should think about other approach in this case, what is the best way to solve this issue?

Don't mix lifetimes. The repository factory can be scoped too. The performance penalty is minimal.

By doing that change you can simply take in the Unit Of Work in the repository factory constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM