Caliburn.Micro使用Autofac

该代码段展示了如何在WPF应用程序中使用Autofac作为依赖注入容器,并结合Caliburn.Micro进行事件管理和视图模型绑定。配置包括数据库注册、日志记录、服务注册以及视图模型的注册,确保了应用程序的组件化和解耦。
摘要由CSDN通过智能技术生成
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
    {

    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值