//==============================================================
//  版权所有：深圳杰文科技
//  文件名：DbServiceContainer.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2017-11-28 16:18
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.Diagnostics;
using Framework.Common;
using Infrastructure.Log;
using Infrastructure.Utilities;

namespace Framework.HandlerBase
{
	//[DebuggerStepThrough]
	public class DbServiceContainer : IDbServiceContainer, IDisposable
	{
		private IDB db = null;
		private string dbName = "db";

		public DbServiceContainer(IDB db)
		{
			this.db = db;
		}

		public T Create<T>() where T : new()
		{
			return RealCreate<T>("db");
		}

		public T Create<T>(string dbName) where T : new()
		{
			return RealCreate<T>(dbName);
		}

		private T RealCreate<T>(string dbName) where T : new()
		{
			this.dbName = dbName;

			IUser user = ServiceContext.GetCurrentUser();
			ReflectHelper.SetProperty(db, "CurrentUser", user);
			ReflectHelper.SetProperty(db, "ServiceContainer", this);

			T obj = new T();

			try
			{
				ReflectHelper.SetField(obj, this.dbName, db);
			}
			catch (Exception ex)
			{
				throw new ServiceException("初始化db属性错误：\r\n{0}", ex.Message);
			}

			ReflectHelper.InvokeMethod(obj, "Init");

			return obj;
		}

		private bool disposed = false;

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!this.disposed)
			{
				disposed = true;
			}
		}

		~DbServiceContainer()
		{
			Dispose(false);
		}

	}
}
