3. 在启动时添加 EngineContext.Initialize(false),启动项目,报错了,因为winform不能执行,对方法做些调整,添加一个参数isForm表示是否是winform,默认为false。
/// <summary> /// Initializes a static instance of the Nop factory. /// </summary> /// <param>Creates a new factory instance even though the factory has been previously initialized.</param> /// <param>是否客户端程序</param> [MethodImpl(MethodImplOptions.Synchronized)] public static IEngine Initialize(bool forceRecreate,bool isWinForm = false) { if (Singleton<IEngine>.Instance == null || forceRecreate) { Singleton<IEngine>.Instance = new NopEngine(); NopConfig config = null; if (!isWinForm) { config = ConfigurationManager.GetSection("NopConfig") as NopConfig; } else { //如果使用winform,使用此代码读取配置初始化NopConfig var appSettings = ConfigurationManager.AppSettings; foreach (var key in appSettings.AllKeys) { } } Singleton<IEngine>.Instance.Initialize(config); } return Singleton<IEngine>.Instance; }
static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Form1()); //引擎上下文初始化 EngineContext.Initialize(false, true); Application.Run(EngineContext.Current.Resolve<Form1>()); } }
4. From1中测试,成功调用了业务层的方法,这里我们并没有实例化ITestService,而是交给依赖注入自动实现。
public partial class Form1 : Form, IRegistrarForm { private ITestService _testService; public Form1( ITestService testService ) { InitializeComponent(); _testService = testService; //如果不注入form可以使用EngineContext.Current.Resolve<ITestService>(); 得到实例 } private void button1_Click(object sender, EventArgs e) { var tests = _testService.GetAllTests(); } }
至此,基于Nop的精简开发框架基本完成,如果你有兴趣,建议在github关注该项目 :https://github.com/dreling8/Nop.Framework,欢迎star给星星,你的支持是我的动力!