csharp 在asp.net mvc中实现工作单元模式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 在asp.net mvc中实现工作单元模式相关的知识,希望对你有一定的参考价值。

using didongexpress.entities;
using didongexpress.repos.Repos;
using System;
using System.Collections.Generic;

namespace didongexpress.repos
{
    public interface IUnitOfWork : IDisposable
    {
        bool SaveChanges();
        TRepository Get<TRepository>() where TRepository : class, IRepository;
    }

    public class UnitOfWork : IUnitOfWork
    {
        private readonly Dictionary<Type, Lazy<IRepository>> _repoFactory = null;
        private readonly Lazy<ExpressDb> _db = null;

        public UnitOfWork()
        {
            _db = new Lazy<ExpressDb>(() => new ExpressDb());
            _repoFactory = new Dictionary<Type, Lazy<IRepository>>
            {
                { typeof (IProductRepository), new Lazy<IRepository>(() => new ProductRepository(_db.Value)) }
            };
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public TRepository Get<TRepository>() where TRepository : class, IRepository
        {           
            if (!_repoFactory.ContainsKey(typeof(TRepository)))
            {
                throw new Exception($"Repository type ${typeof(TRepository)} have not been registered yet!");
            }

            return _repoFactory[typeof(TRepository)] as TRepository;
        }

        public bool SaveChanges()
        {            
            return true;
        }
    }
}

以上是关于csharp 在asp.net mvc中实现工作单元模式的主要内容,如果未能解决你的问题,请参考以下文章