using Autofac;
using Caliburn.Micro;
namespace ST.ERMS.AutFac
{
public class AutFacContainer : BootstrapperBase
{
/// <summary>
///
/// </summary>
private IContainer container;
/// <summary>
///
/// </summary>
private ContainerBuilder builder;
/// <summary>
/// 记录日志
/// </summary>
private ILogEntity runLog;
public AutFacContainer()
{
Initialize();
}
private void BuilderContainer()
{
builder = new ContainerBuilder();
#region 注册配置
var config = this.BuildConfig();
builder.RegisterInstance(config);
#endregion
#region 注册日志
//builder.RegisterType<LogProviderOfLog4net>().As<ILogProvider>();
#endregion
#region 注册缓存
//builder.RegisterType<DefaultCacheManager>().As<ICacheManagerService>().SingleInstance();
//builder.RegisterType<DefaultCacheProvider>().As<ICacheProvider>().SingleInstance();
#endregion
#region 注册freesql
RegisterDb<ERMSDbContext>(builder, config, true);
#endregion
// 注册服务
builder.RegisterType<CommNetServer>().SingleInstance();
// 注册单例用户
builder.RegisterType<LoginUserInfo>().SingleInstance();
// 注册加密类
builder.RegisterType<EncryptHelper>().As<IEncryptHelper>().SingleInstance();
//#region 注册日志
builder.RegisterType<RunLog>().As<ILogEntity>().InstancePerLifetimeScope();
//#endregion
//AppDomain.CurrentDomain.Load("ST.ERMS");
var allAssemblies = AppDomain.CurrentDomain.GetAssemblies();
var assembiles = allAssemblies.Where(x => x.ManifestModule.Name.Contains("ST.ERMS")).ToArray();
#region 注册服务
builder.RegisterAssemblyTypes(allAssemblies)
.Where(type => typeof(ITransient).IsAssignableFrom(type) && !type.IsAbstract)
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
#endregion
#region 注册视图模型
builder.RegisterType<PropertyChangedBase>().InstancePerLifetimeScope();
builder.RegisterType<WindowManager>().As<IWindowManager>().SingleInstance();
builder.RegisterType<EventAggregator>().As<IEventAggregator>().InstancePerLifetimeScope();
builder.RegisterType<AppMainShellViewModel>().As<IAppBaseShell>().InstancePerLifetimeScope();
builder.RegisterAssemblyTypes(allAssemblies)
.Where(type => typeof(BaseListViewModel).IsAssignableFrom(type) && !type.IsAbstract)
.AsSelf();
builder.RegisterAssemblyTypes(allAssemblies)
.Where(type => typeof(Caliburn.Micro.Screen).IsAssignableFrom(type) && !type.IsAbstract)
.AsSelf();
#endregion
}
/// <summary>
/// 构建配置
/// </summary>
/// <returns></returns>
private ConfigInfo BuildConfig()
{
string temp = string.Empty;
var config = new ConfigInfo();
config.WMSConn = ConfigurationManager.ConnectionStrings["WMSConn"].ConnectionString;
config.ProviderName = ConfigurationManager.ConnectionStrings["WMSConn"].ProviderName;
config.DBType = ConfigurationManager.AppSettings["DBType"].Trim();
return config;
}
/// <summary>
/// 注册数据库
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="builder"></param>
/// <param name="cfg"></param>
/// <param name="useAutoSyncStructure"></param>
private void RegisterDb<T>(ContainerBuilder builder, ConfigInfo cfg, bool useAutoSyncStructure) where T : BaseDbContext
{
var build = new FreeSql.FreeSqlBuilder();
var dbType = FreeSql.DataType.SqlServer;
if (!string.IsNullOrEmpty(cfg.ProviderName))
{
if (cfg.ProviderName.ToLower() == "mysql.data.mysqlclient")
dbType = FreeSql.DataType.MySql;
else if (cfg.ProviderName.ToLower() == "system.data.sqlite")
dbType = FreeSql.DataType.Sqlite;
}
else
{
if (cfg.DBType.ToUpper() == "MYSQL")
{
dbType = FreeSql.DataType.MySql;
}
else if (cfg.DBType == "SQLITE")
{
dbType = FreeSql.DataType.Sqlite;
}
}
build = build.UseConnectionString(dbType, cfg.WMSConn);
IFreeSql freeSql = build.UseAutoSyncStructure(useAutoSyncStructure)
.UseMonitorCommand(
cmd =>
{
string commandText = cmd.CommandText;
//RunLog log = new RunLog();
//log.LogInfo2File("执行前:\r\n" + commandText);
Console.WriteLine(cmd.CommandText);
}, //监听SQL命令对象,在执行前
(cmd, traceLog) =>
{
string traceLogText = traceLog;
//RunLog log = new RunLog();
//log.LogInfo2File("执行后:\r\n" + traceLog);
//Console.WriteLine(traceLog);
}) //监听SQL命令对象,在执行后
//.UseLazyLoading(true)
.Build();
builder.RegisterInstance(freeSql).SingleInstance();
builder.RegisterType<T>()
.WithParameter(new NamedParameter("freeSql", freeSql) { })
.InstancePerLifetimeScope();
// AOP拦截
freeSql.Aop.CurdBefore += (s, e) =>
{
if (e.CurdType == FreeSql.Aop.CurdType.Delete)
{
}
};
}
protected override void Configure()
{
BuilderContainer();
container = builder.Build();
runLog = container.Resolve<ILogEntity>();
}
protected override object GetInstance(Type service, string key)
{
try
{
return key == null ? container.Resolve(service) : container.ResolveNamed(key, service);
}
catch(Exception ex)
{
runLog.LogError2File("GetInstance: " + ex.Message);
}
try
{
return base.GetInstance(service, key);
}
catch (Exception ex)
{
runLog.LogError2File("GetInstance: " + ex.Message);
}
return null;
}
protected override IEnumerable<object> GetAllInstances(Type service)
{
try
{
var type = typeof(IEnumerable<>).MakeGenericType(service);
return container.Resolve(type) as IEnumerable<object>;
}
catch(Exception ex)
{
runLog.LogError2File("GetAllInstances: " + ex.Message);
}
try
{
return base.GetAllInstances(service);
}
catch (Exception ex)
{
runLog.LogError2File("GetAllInstances: " + ex.Message);
}
return null;
}
protected override void BuildUp(object instance)
{
try
{
container.InjectProperties(instance);
}
catch (Exception ex)
{
runLog.LogError2File("BuildUp: " + ex.Message);
base.BuildUp(instance);
}
}
protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
{
// 不带登录窗口
//DisplayRootViewFor<IAppBaseShell>();
//System.Windows.Application app = ((System.Windows.Application)(sender));
//if (app != null && app.Windows != null && app.Windows.Count > 0)
//{
// app.Windows[0].WindowState = System.Windows.WindowState.Maximized;
//}
// https://stackoverflow.com/questions/11966698/how-do-i-handle-login-logout-in-caliburn-micro
var vm = IoC.Get<LoginViewModel>();
vm.LoginSuccessful =
() => GuardCloseAndReopen(sender, e, vm);
var windowManager = IoC.Get<IWindowManager>();
var result = Utils.OpenDialog(windowManager, vm);
}
private void GuardCloseAndReopen(object sender, System.Windows.StartupEventArgs e, Caliburn.Micro.Screen vm)
{
DisplayRootViewFor<IAppBaseShell>();
System.Windows.Application app = ((System.Windows.Application)(sender));
if (app != null && app.Windows != null && app.Windows.Count > 0)
{
foreach(Window item in app.Windows)
{
if (item is AppMainShellView)
{
item.WindowState = System.Windows.WindowState.Maximized;
break;
}
}
}
//Application.ShutdownMode = ShutdownMode.OnExplicitShutdown;
vm.TryCloseAsync(true);
//Application.ShutdownMode = ShutdownMode.OnLastWindowClose;
}
protected override void OnExit(object sender, EventArgs e)
{
}
protected override void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
e.Handled = true;
runLog.LogError2File("OnUnhandledException: " + e.Exception.Message);
}
}
public interface IAppBaseShell
{
}
}